Skip to content

Commit 912539a

Browse files
authored
Don't replace unused variables with None (#2396)
1 parent f0251db commit 912539a

14 files changed

Lines changed: 60 additions & 58 deletions

notebooks/liger_kernel.ipynb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@
251251
},
252252
{
253253
"cell_type": "code",
254-
"execution_count": 7,
254+
"execution_count": null,
255255
"id": "32cd98f0-a36f-4e01-8ae4-6e36adf2699b",
256256
"metadata": {},
257257
"outputs": [],
@@ -322,11 +322,12 @@
322322
" while bound_symbols:\n",
323323
" bsym = bound_symbols.pop(0)\n",
324324
" if bsym.sym == litgpt_apply_rope:\n",
325-
" for i, bsym2 in enumerate(bound_symbols):\n",
325+
" while bound_symbols:\n",
326+
" bsym2 = bound_symbols.pop(0)\n",
326327
" assert not any(o is bsym.output for o in bsym2.flat_outs)\n",
327328
" if bsym2.sym == litgpt_apply_rope:\n",
328329
" break\n",
329-
" bsym2 = bound_symbols.pop(i)\n",
330+
" new_compute_trace.bound_symbols.append(bsym2.from_bsym())\n",
330331
" assert bsym2.sym == litgpt_apply_rope\n",
331332
"\n",
332333
" output = (bsym.output, bsym2.output)\n",

thunder/core/symbol.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,16 @@
1414
from collections.abc import Sequence
1515

1616
import thunder.core.baseutils as baseutils
17+
from thunder.core.baseutils import BoundSymbolInterface, TagBase
1718
import thunder.core.codeutils as codeutils
1819
from thunder.core.codeutils import Printable, Positions
19-
from thunder.core.baseutils import BoundSymbolInterface, TagBase
20-
from thunder.core.utils import FrozenDict, make_hashable
21-
from thunder.core.pytree import tree_flatten_with_dataclass, tree_unflatten, tree_map
22-
from thunder.core.proxies import Proxy, TensorProxy, variableify, CollectionProxy, ProxyTag
2320
from thunder.core.compile_data import get_compile_data
21+
import thunder.core.prims as prims
22+
from thunder.core.proxies import Proxy, TensorProxy, variableify, CollectionProxy, ProxyTag
23+
from thunder.core.pytree import tree_flatten, tree_flatten_with_dataclass, tree_unflatten, tree_map
24+
from thunder.core.trace import get_tracectx, VariableInterface
25+
from thunder.core.utils import FrozenDict, make_hashable
2426

25-
from thunder.core.trace import (
26-
get_tracectx,
27-
VariableInterface,
28-
)
2927

3028
#
3129
# Support for querying "traceable" functions
@@ -314,6 +312,17 @@ def __call__(self, *args, **kwargs):
314312
else:
315313
trace.push_scope(subsymbols)
316314
result = self.meta(*args, **kwargs)
315+
316+
# To avoid passing an arg directly to output, we make a shallow_copy
317+
flat_results, spec = tree_flatten(result)
318+
flat_args, _ = tree_flatten((args, kwargs))
319+
for i, result_ in enumerate(flat_results):
320+
for arg in flat_args:
321+
if arg is result_ and isinstance(arg, Proxy):
322+
flat_results[i] = prims.shallow_copy(arg)
323+
324+
result = tree_unflatten(flat_results, spec)
325+
317326
trace.pop_scope()
318327

319328
cd = get_compile_data()

thunder/core/transform_common.py

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -162,29 +162,14 @@ def dce(trace: Trace, needed_proxies: None | set[Variable] = None) -> Trace:
162162
else:
163163
needed = False
164164

165-
# NOTE This block is run even if we know we're preserving the operation, because it
166-
# may mark some of the operation's outputs as unused
167-
some_unused = False
168165
for out in bsym.flat_proxy_outs:
169166
if variableify(out) in needed_proxies and producer_map[out] == bsym:
170167
needed = True
171-
else:
172-
some_unused = True
168+
break
173169

174170
if needed:
175171
nbsym: BoundSymbol = bsym
176172

177-
# Replaces unused Proxy outputs with None
178-
if some_unused:
179-
180-
def _helper(x):
181-
if isinstance(x, Proxy) and (variableify(x) not in needed_proxies or producer_map[x] != bsym):
182-
return None
183-
return x
184-
185-
nbsym_output = tree_map(_helper, bsym.output)
186-
nbsym = bsym.from_bsym(output=nbsym_output)
187-
188173
# Eliminates no-op subsymbols
189174
# NOTE In general editing subsymbols doesn't do anything, but no-op subsymbols are a pain
190175
# for transforms to deal with. Transforms typically look for a "flattened" version of an

thunder/core/transforms.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,16 @@ def _cat_prim_grad(tensors: list[TensorProxy], /, dim: int) -> TensorProxy:
750750
register_grad(pids.CAT, _cat_prim_grad)
751751

752752

753+
def _shallow_copy_prim_grad(a: TensorProxy) -> TensorProxy:
754+
fwd = prims.shallow_copy(a)
755+
g = get_grad(fwd)
756+
put_grad(a, g)
757+
return fwd
758+
759+
760+
register_grad(pids.SHALLOW_COPY, _shallow_copy_prim_grad)
761+
762+
753763
def _update_aliases_prim_grad(tensors: tuple[TensorProxy, ...]) -> tuple[TensorProxy, ...]:
754764
fwd_tensors = prims.update_aliases(tensors)
755765
for fwd_t, t in zip(fwd_tensors, tensors):

thunder/examine/memory_calculation.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"contiguous",
2727
"split",
2828
"torch_wait_prim_impl",
29+
"shallow_copy",
2930
)
3031

3132
# A registry of symbols that require special memory calculation;

thunder/executors/nvfuserex_impl.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1764,6 +1764,16 @@ def clone(a: TensorProxy, *, fd: FusionDefinition, lc_to_nv_map: dict) -> Any:
17641764

17651765
register_supported(PrimIDs.CLONE, clone, _elementwise_unary_check)
17661766

1767+
1768+
def shallow_copy(a: TensorProxy, *, fd: FusionDefinition, lc_to_nv_map: dict) -> Any:
1769+
nva = getnv(a, fd, lc_to_nv_map)
1770+
1771+
return nva
1772+
1773+
1774+
register_supported(PrimIDs.SHALLOW_COPY, shallow_copy, _elementwise_unary_check)
1775+
1776+
17671777
# update_aliases is disabled. nvfuser does not support it.
17681778
# TODO: Enable this once nvfuser supports it.
17691779
# def update_aliases(aliases: tuple[TensorProxy], *, fd: FusionDefinition, lc_to_nv_map: dict) -> Any:

thunder/executors/torch_compile.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ def cuda_device_checker(*args, **kwargs):
227227
# parallel residual paths are used in the transformer block
228228
prims.div.id,
229229
prims.erf.id,
230+
prims.shallow_copy.id,
230231
}
231232
torch_compile_cat_ex._implmap = {
232233
op: ImplInfo(checker=cuda_device_checker) for op in pytorch_ex.implmap if op in supported_ops

thunder/tests/opinfos.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,12 @@ def _abs_torch(x: torch.Tensor | Number):
695695
dtypes=(datatypes.complex32,),
696696
devicetypes=(devices.DeviceType.CPU,),
697697
),
698+
DecorateInfo(
699+
pytest.mark.skip(reason="PyTorch doesn't support abs for bool on cpu"),
700+
"test_core_vs_torch_consistency",
701+
dtypes=(datatypes.bool8,),
702+
devicetypes=(devices.DeviceType.CPU,),
703+
),
698704
# Ref - https://github.com/Lightning-AI/lightning-thunder/issues/2363
699705
DecorateInfo(
700706
pytest.mark.skip,

thunder/tests/test_core.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,28 +2111,6 @@ def func(qkv):
21112111
assert "scaled_dot_product_attention" in tuple(bsym.sym.id for bsym in traces[-1].bound_symbols)
21122112

21132113

2114-
@instantiate(dtypes=NOTHING)
2115-
def test_no_passthrough_symbol(executor, device, _):
2116-
# A test case for the situation reported in
2117-
# "backward trace contains symbols not present in forward that cause
2118-
# NotImplementedError"
2119-
# When an operation simply passes through its input, we should not
2120-
# add it to the trace.
2121-
2122-
def func(x):
2123-
return x.type_as(x)
2124-
2125-
x = make_tensor((2, 2), device=device, dtype=torch.float32)
2126-
compiled = executor.make_callable(func)
2127-
out = compiled(x)
2128-
assert out is x
2129-
initial_trace_with_dce = thunder.last_traces(compiled)[3]
2130-
assert "Constructed by Dead Code Elimination" in str(initial_trace_with_dce)
2131-
assert len(initial_trace_with_dce.bound_symbols) == 2
2132-
assert initial_trace_with_dce.bound_symbols[0].sym.id == prims.PrimIDs.UNPACK_TRIVIAL
2133-
assert initial_trace_with_dce.bound_symbols[1].sym.id == prims.PrimIDs.RETURN
2134-
2135-
21362114
@instantiate(
21372115
dtypes=NOTHING,
21382116
# https://github.com/Lightning-AI/lightning-thunder/issues/946

thunder/tests/test_examine_memory.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,5 +113,5 @@ def test_nanogpt_block():
113113
# We are checking the estimated memory against a fixed value for consistency.
114114
assert max_mem_fw[0] == 381754368
115115
assert sum(max_mem_fw[1].values()) == 375462912
116-
assert max_mem_bw[0] == 641097728
117-
assert sum(max_mem_bw[1].values()) == 440474624
116+
assert max_mem_bw[0] == 741761024
117+
assert sum(max_mem_bw[1].values()) == 541137920

0 commit comments

Comments
 (0)