1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
|
# mypy: allow-untyped-defs
import argparse
import copy
import functools
import io
import logging
import os
import shutil
import subprocess
import sys
import textwrap
import uuid
from importlib import import_module
from tempfile import TemporaryFile
from typing import Any, Callable, Dict, Sequence, TYPE_CHECKING, Union
from typing_extensions import Unpack
import torch
import torch.fx as fx
import torch.nn as nn
from torch._dynamo.debug_utils import (
_cuda_system_info_comment,
AccuracyError,
backend_accuracy_fails,
BuckTargetWriter,
cast_to_fp64,
extra_deps,
extra_imports,
generate_config_string,
helper_for_dump_minify,
InputReader,
InputWriter,
MAX_CONSTANT_NUMEL_INLINE,
minifier_dir,
NNModuleToString,
NopInputReader,
same_two_models,
)
from torch._dynamo.trace_rules import is_fbcode
from torch._dynamo.utils import clone_inputs, counters, same
from torch._inductor.output_code import OutputCode
from torch.fx.experimental.proxy_tensor import make_fx
from torch.fx.experimental.symbolic_shapes import (
fx_placeholder_targets,
has_free_symbols,
)
from torch.hub import tqdm
from .. import config
if TYPE_CHECKING:
from torch._inductor.compile_fx import _CompileFxCallable, _CompileFxKwargs
from torch._inductor.utils import InputType
log = logging.getLogger(__name__)
inductor_config = import_module("torch._inductor.config")
use_buck = inductor_config.is_fbcode()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# MAIN ENTRY POINT
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def wrap_compiler_debug(
unconfigured_compiler_fn: "_CompileFxCallable",
compiler_name: str,
) -> "_CompileFxCallable":
"""
Minifier for Fx Graph modules after Aot Autograd has finished. We wrap both
forward and backward call separately with the backend compiler_fn - like
inductor or nvfuser. Intercepting after Aot Autograd presents neat
abstraction, where all the params are lifted as graph inputs, making it easy
to save the graph as a string.
"""
@functools.wraps(unconfigured_compiler_fn)
def debug_wrapper(
gm: torch.fx.GraphModule,
example_inputs: Sequence["InputType"],
**kwargs: Unpack["_CompileFxKwargs"],
) -> OutputCode:
from torch._subclasses import FakeTensorMode
compiler_fn = functools.partial(unconfigured_compiler_fn, **kwargs)
from torch._functorch.aot_autograd import get_aot_graph_name
graph_name = get_aot_graph_name()
# TODO: why do we need to deepcopy the original graph?
orig_graph = copy.deepcopy(gm.graph)
assert config.repro_after in ("dynamo", "aot", None)
try:
# Call the compiler_fn - which is either aot_autograd or inductor
# with fake inputs
inner_compiled_fn = compiler_fn(gm, example_inputs)
except Exception as e:
# TODO: Failures here are troublesome because no real inputs,
# need a different serialization strategy
if config.repro_after == "aot":
if config.repro_level == 1:
dump_compiler_graph_state(
fx.GraphModule(gm, orig_graph),
example_inputs,
compiler_name,
)
elif config.repro_level == 2:
dump_to_minify(
fx.GraphModule(gm, orig_graph),
example_inputs,
compiler_name,
)
log.error("CompilerError")
raise
# We may run regular PyTorch compute that may trigger Dynamo, do NOT
# recursively attempt to accuracy minify in that case!
def deferred_for_real_inputs(
real_inputs: Sequence["InputType"], **_kwargs: object
) -> Any:
# This is a bit obscure: if we recursively try to accuracy minify
# the SAME function, this would trigger. But most of the time
# we should never hit this branch
assert not _kwargs
if config.repro_after != "aot":
assert not isinstance(inner_compiled_fn, str)
return inner_compiled_fn(real_inputs)
with config.patch(repro_after=None):
return inner_debug_fn(real_inputs)
def inner_debug_fn(real_inputs):
"""
Aot Autograd fw_compiler and bw_compiler can have fake tensors. So,
example_inputs can be fake tensors. We can call compiler_fn (which is
inductor or nvfuser) with fake tensors but the actually compiled_fn
should be called with real tensors. Therefore, the actual invocation
is deferred.
"""
# Copy the tensor attrs like shape, stride etc by converting to Fake Tensor
# because inductor clears the tensor list in its codegen. And example_inputs
# are available only for the first invocation.
fake_mode = FakeTensorMode()
copy_tensor_attrs = [
fake_mode.from_tensor(x) if isinstance(x, torch.Tensor) else x
for x in real_inputs
]
if config.repro_level == 3:
# Always dump the original module in case we have segfaults
dump_to_minify(
fx.GraphModule(gm, orig_graph), real_inputs, compiler_name
)
if config.repro_level == 4:
if compiler_name != "inductor":
raise NotImplementedError(
"Accuracy minification is supported for inductor only"
)
failed = not same_two_models(
gm,
inner_compiled_fn,
real_inputs,
only_fwd=True,
ignore_non_fp=config.repro_ignore_non_fp,
)
if failed:
log.warning(
"Accuracy failed for the AOT Autograd graph %s", graph_name
)
dump_compiler_graph_state(
fx.GraphModule(gm, orig_graph),
real_inputs,
f"{compiler_name}_accuracy",
)
dump_to_minify(
fx.GraphModule(gm, orig_graph),
real_inputs,
f"{compiler_name}_accuracy",
)
raise AccuracyError("Bad accuracy detected")
else:
# Call the compiled function with real inputs
return inner_compiled_fn(real_inputs) # type: ignore[operator]
else:
try:
# Call the compiled function with real inputs
out = inner_compiled_fn(real_inputs) # type: ignore[operator]
# sync cuda kernels to ensure IMA detection
for arg in example_inputs:
if isinstance(arg, torch.Tensor) and arg.is_cuda:
torch.cuda.synchronize()
break
return out
except Exception as e:
if config.repro_level == 1:
dump_compiler_graph_state(
fx.GraphModule(gm, orig_graph),
copy_tensor_attrs,
compiler_name,
)
elif config.repro_level == 2:
dump_to_minify(
fx.GraphModule(gm, orig_graph),
copy_tensor_attrs,
compiler_name,
)
raise
if config.repro_after == "aot":
compiled_fn = deferred_for_real_inputs
compiled_fn._boxed_call = True # type: ignore[attr-defined]
return compiled_fn # type: ignore[return-value]
else:
return inner_compiled_fn
return debug_wrapper
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# DUMP REPROS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def maybe_fbcode_instructions():
if is_fbcode:
extra_deps_formatted = "\n".join([f' "{dep}",' for dep in extra_deps])
if len(extra_deps_formatted) > 0:
extra_deps_formatted = "\n" + extra_deps_formatted
return f"""\
\"\"\"
To run this script in fbcode:
- Create a directory (//scripts/{{your_unixname}}/repro)
- Put this file in scripts/{{your_unixname}}/repro/fx_graph_runnable.py
- Add a TARGETS file that looks like the following
- `buck2 run //scripts/{{your_unixname}}/repro:repro`
NOTE: you may need additional deps to actually be able to run the script.
```
# Contents of TARGETS file
load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary")
python_binary(
name = "repro",
main_src = "fx_graph_runnable.py",
deps = [
"//caffe2:torch",{extra_deps_formatted}
],
)
```
\"\"\"
"""
else:
return ""
def generate_compiler_repro_string(
gm, args, *, stable_output=False, save_dir=None, stable_hash=False
):
model_str = textwrap.dedent(
f"""
import torch
from torch import tensor, device
import torch.fx as fx
from torch._dynamo.testing import rand_strided
from math import inf
import torch._inductor.inductor_prims
{generate_config_string(stable_output=stable_output)}
isolate_fails_code_str = None
{extra_imports}
{maybe_fbcode_instructions()}
"""
)
if not stable_output:
model_str += f"# torch version: {torch.version.__version__}\n"
if hasattr(torch.version, "cuda"):
model_str += f"# torch cuda version: {torch.version.cuda}\n"
if hasattr(torch.version, "git_version"):
model_str += f"# torch git version: {torch.version.git_version}\n\n\n"
model_str += _cuda_system_info_comment()
model_str += NNModuleToString.convert(gm)
# get hint shape/stride when dynamic shape enabled
def hint_if_symint(x):
return tuple(i.node.hint if isinstance(i, torch.SymInt) else i for i in x)
writer = InputWriter(save_dir, stable_hash=stable_hash)
for placeholder, arg in zip(fx_placeholder_targets(gm), args):
if isinstance(arg, (int, torch.SymInt)):
writer.symint(placeholder, arg)
elif isinstance(arg, torch.Tensor):
# TODO: improve these names with FQN
writer.tensor(placeholder, arg)
elif arg is None:
writer.const(placeholder)
else:
# It's better to produce a slightly wrong repro string than none
# at all
writer.unsupported(placeholder, arg)
model_str += "\n".join(writer.lines()) + "\n"
model_str += "mod = Repro()\n"
return model_str
def save_graph_repro(
fd,
gm,
args,
compiler_name,
*,
stable_output=False,
save_dir=None,
command="run",
accuracy=None,
tracing_mode=None,
check_str=None,
stable_hash=False,
):
if any(
isinstance(arg, torch.fx.experimental._backward_state.BackwardState)
for arg in args
):
fd.write(
"Repro is not generated due to existence of BackwardState in graph input"
)
return
fd.write(
generate_compiler_repro_string(
gm,
args,
stable_output=stable_output,
save_dir=save_dir,
stable_hash=stable_hash,
)
)
if accuracy is None:
accuracy = "_accuracy" in compiler_name
if tracing_mode is None:
tracing_mode = "real"
if any(has_free_symbols(a) for a in args):
tracing_mode = "symbolic"
fd.write("if __name__ == '__main__':\n")
fd.write(" from torch._dynamo.repro.after_aot import run_repro\n")
fd.write(
f" with torch.no_grad():\n"
f" run_repro(mod, load_args, accuracy={accuracy!r}, command={command!r}, "
f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n"
f" # To run it separately, do \n"
f" # mod, args = run_repro(mod, load_args, accuracy={accuracy!r}, command='get_args', "
f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n"
f" # mod(*args)"
)
def dump_compiler_graph_state(gm, args, compiler_name, *, accuracy=None):
subdir = os.path.join(minifier_dir(), "checkpoints")
if not os.path.exists(subdir):
os.makedirs(subdir, exist_ok=True)
file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py")
log.warning(
"Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name
)
with open(file_name, "w") as fd:
save_graph_repro(
fd, gm, args, compiler_name, save_dir=subdir, accuracy=accuracy
)
curdir = os.getcwd()
repro_path = os.path.join(curdir, "repro.py")
try:
shutil.copyfile(file_name, repro_path)
log.warning("Copying repro file for convenience to %s", repro_path)
if use_buck:
BuckTargetWriter(file_name).write()
except OSError:
log.warning("No write permissions for %s", repro_path)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# DUMP MINIFIER
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def dump_to_minify(gm, args, compiler_name: str):
out = io.StringIO()
# TODO: factor this out
subdir = os.path.join(minifier_dir(), "checkpoints")
if not os.path.exists(subdir):
os.makedirs(subdir, exist_ok=True)
save_graph_repro(out, gm, args, compiler_name, save_dir=subdir, command="minify")
return helper_for_dump_minify(out.getvalue())
def isolate_fails(
fx_g,
args,
compiler_name: str,
env=None,
save_dir=None,
accuracy=None,
tracing_mode=None,
check_str=None,
):
if env is None:
env = {}
subdir = os.path.join(os.getcwd(), "isolate")
if not os.path.exists(subdir):
os.makedirs(subdir, exist_ok=True)
file_name = os.path.join(subdir, f"{str(uuid.uuid4())[:5]}.py")
with open(file_name, "w") as fd:
save_graph_repro(
fd,
fx_g,
args,
compiler_name,
save_dir=save_dir,
command="minifier-query",
accuracy=accuracy,
tracing_mode=tracing_mode,
check_str=check_str,
)
# with open(file_name, "r") as fd:
# print(fd.read())
new_env = os.environ.copy()
new_env = {**new_env, **env}
stdout, stderr = TemporaryFile(), TemporaryFile()
if use_buck:
cmd = BuckTargetWriter(file_name).write(print_msg=False)
else:
cmd = ["python", file_name]
p = subprocess.Popen(
cmd,
cwd=subdir,
stdout=stdout,
stderr=stderr,
env=new_env,
)
p.wait()
stdout.seek(0)
stderr.seek(0)
print(
textwrap.indent(stdout.read().decode("utf-8"), prefix=">> "), file=sys.stdout
)
print(
textwrap.indent(stderr.read().decode("utf-8"), prefix=">> "), file=sys.stderr
)
# print(f"Isolated test failed - {file_name}")
return p.returncode != 0
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# MINIFIER TOOLS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def inductor_fails(fx_g, args, check_str=None):
has_cuda = False
for arg in args:
if isinstance(arg, torch.Tensor) and arg.is_cuda:
has_cuda = True
break
def sync():
if has_cuda:
# Ensures that segfaults are surfaced
torch.cuda.synchronize()
from torch._inductor.compile_fx import compile_fx_inner
try:
result = fx_g(*args)
assert isinstance(result, (tuple, list))
assert not any(isinstance(x, (tuple, list)) for x in result)
except Exception:
return False
sync()
try:
compile_mod = compile_fx_inner(fx_g, args)
assert not isinstance(compile_mod, str)
compile_mod(args)
sync()
except Exception as e:
if check_str is not None and check_str not in repr(e):
return False
print(repr(e))
return True
return False
def inductor_accuracy_fails(
fx_g, args, check_str=None, *, require_fp64=False, ignore_non_fp=False
):
from torch._inductor.compile_fx import compile_fx_inner
return backend_aot_accuracy_fails(
fx_g,
args,
compile_fx_inner,
require_fp64=require_fp64,
ignore_non_fp=ignore_non_fp,
)
backend_aot_accuracy_fails = functools.partial(backend_accuracy_fails, only_fwd=True)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# REPRO MAIN
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def repro_common(options, mod, load_args):
# Invariant for graphs we generate with the repro script
assert not any(mod.named_parameters())
for n, b in mod.named_buffers():
if b.numel() > MAX_CONSTANT_NUMEL_INLINE:
log.warning(
"Constant %s was not serialized, generated random data instead. "
"If you think this is affecting you, please comment on "
"https://github.com/pytorch/pytorch/issues/100468",
n,
)
if not hasattr(load_args, "_version"):
log.warning(
"load_args does not have a _version attribute, please file a bug to PyTorch "
"and describe how you generate this repro script"
)
else:
if load_args._version > 0:
log.warning(
"load_args is version %s, but this version of PyTorch only supports "
"version 0. We will try to run it anyway but there may be an incompatibility; "
"if so, try upgrading your version of PyTorch.",
load_args._version,
)
nop_reader = NopInputReader()
load_args(nop_reader)
with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar:
input_reader = InputReader(save_dir=options.save_dir, pbar=pbar)
load_args(input_reader)
args = input_reader.args
# Turn mod into a GraphModule the slow way
# TODO: speed this up
mod = make_fx(mod, tracing_mode=options.tracing_mode)(*args)
torch._inductor.config.generate_intermediate_hooks = True
return mod, args
ACCURACY_FAILS: Dict[str, Callable[[nn.Module, Any], bool]] = {
"": inductor_fails,
# This might look inverted but it's not. strict_accuracy means "we will
# minify any time we see anything that diverges", whereas accuracy is more
# conservative, and will only minify if there is a meaningful fp64
# divergence
"accuracy": functools.partial(
inductor_accuracy_fails, require_fp64=True, ignore_non_fp=True
),
"strict_accuracy": inductor_accuracy_fails,
}
def repro_minifier_query(options, mod, load_args):
mod, args = repro_common(options, mod, load_args)
fail_fn = functools.partial(
ACCURACY_FAILS[options.accuracy], check_str=options.check_str # type: ignore[call-arg]
)
if fail_fn(mod, args):
sys.exit(1)
else:
sys.exit(0)
def repro_minify(options, mod, load_args):
from functorch.compile import minifier
mod, args = repro_common(options, mod, load_args)
compiler_name = "inductor_accuracy" if options.accuracy != "" else "inductor"
favored_device = 1 if torch.cuda.device_count() >= 2 else 0
env_variables = {"CUDA_VISIBLE_DEVICES": str(favored_device)}
module_fails: Any
if options.isolate:
module_fails = functools.partial(
isolate_fails,
env=env_variables,
compiler_name=compiler_name,
save_dir=options.save_dir,
accuracy=options.accuracy,
tracing_mode=options.tracing_mode,
)
else:
module_fails = ACCURACY_FAILS[options.accuracy]
minifier(
mod,
args,
module_fails=functools.partial(module_fails, check_str=options.check_str),
dump_state=functools.partial(
dump_compiler_graph_state, compiler_name=compiler_name
),
save_dir=options.save_dir,
offload_to_disk=options.offload_to_disk,
skip_offload=options.skip_saving_eager_intermediates,
skip_sanity=options.skip_sanity,
max_granularity=options.max_granularity,
)
def repro_analyze(options, mod, load_args):
from torch._inductor.compile_fx import compile_fx_inner
from torch._inductor.hooks import intermediate_hook
mod, args = repro_common(options, mod, load_args)
# TODO: The logic for cloning inputs/models here is intentionally
# modeled off of run_fwd_maybe_bwd, but arguably it is better not to
# clone inputs (as you are doubling your effective GPU memory usage).
# It is certainly faster though! It probably makes sense to let the
# user specify the offload strategy.
with tqdm(desc="Compiling"):
compiled = compile_fx_inner(mod, args)
total = counters["inductor"]["intermediate_hooks"]
known_names = set()
def save_hook(name, val):
known_names.add(name)
if not options.skip_saving_inductor_intermediates:
writer.write_tensor(os.path.join("inductor", name), val)
pbar.update(1) # type: ignore[has-type]
writer = torch.utils._content_store.ContentStoreWriter(
options.save_dir, stable_hash=options.stable_hash
)
reader = torch.utils._content_store.ContentStoreReader(options.save_dir)
new_args = clone_inputs(args)
with intermediate_hook(save_hook), tqdm(
desc="Saving inductor intermediates", total=total
) as pbar:
assert not isinstance(compiled, str)
compiled(new_args)
assert not new_args
def compare_tuples(tuple1, tuple2):
diff_indices = [i for i in range(len(tuple1)) if tuple1[i] != tuple2[i]]
diff_values = [(tuple1[i], tuple2[i]) for i in diff_indices]
if not diff_values:
return None
else:
return " and ".join(f"{a} != {b}" for a, b in diff_values)
def check_hook(name, val):
meta = writer.compute_tensor_metadata(val)
meta2 = reader.read_tensor_metadata(os.path.join("inductor", name))
reason = compare_tuples(meta, meta2)
if reason is not None:
pbar.write(f"NONDETERMINISTIC INDUCTOR at {name} ({reason})")
pbar.update(1)
if not options.skip_check_deterministic:
new_args = clone_inputs(args)
with intermediate_hook(check_hook), tqdm(
desc="Checking inductor determinism", total=total
) as pbar:
compiled(new_args)
assert not new_args
class WriterInterp(fx.Interpreter):
def __init__(self, mod, subdir) -> None:
super().__init__(mod)
self.subdir = subdir
def run_node(self, n):
r = super().run_node(n)
name = n.name
if name in known_names:
pbar.update(1)
writer.write_tensor(os.path.join(self.subdir, name), r)
return r
# NB: the module cast doesn't actually do anything, since there are no
# parameters/buffers on the module
if not options.skip_saving_float64_intermediates:
new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args))
with tqdm(desc="Saving float64 intermediates", total=total) as pbar:
WriterInterp(new_mod, "float64").boxed_run(new_args)
assert not new_args
class ExactReaderInterp(fx.Interpreter):
def run_node(self, n):
r = super().run_node(n)
name = n.name
if name in known_names:
meta = writer.compute_tensor_metadata(r)
meta2 = reader.read_tensor_metadata(os.path.join("float64", name))
reason = compare_tuples(meta, meta2)
if reason is not None:
pbar.write(f"NONDETERMINISTIC FLOAT64 at {name} ({reason})")
pbar.update(1)
return r
# TODO: check eager determinism
if not options.skip_check_deterministic:
new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args))
with tqdm(desc="Checking float64 determinism", total=total) as pbar:
ExactReaderInterp(new_mod).boxed_run(new_args)
assert not new_args
# Now that we've saved everything, interp through the eager graph
# and do comparisons
class ReaderInterp(fx.Interpreter):
def run_node(self, n):
r = super().run_node(n)
name = n.name
if name in known_names:
inductor = reader.read_tensor(os.path.join("inductor", name))
float64 = reader.read_tensor(os.path.join("float64", name))
logged = False
def log_error(msg, *args):
nonlocal logged
logged = True
pbar.write(f"DIVERGED at {name}: {msg % args}")
if not same(
r,
inductor,
float64,
tol=torch._dynamo.config.repro_tolerance,
equal_nan=True,
log_error=log_error,
):
assert logged
pbar.update(1)
return r
with tqdm(desc="Checking divergence", total=total) as pbar:
ReaderInterp(mod).boxed_run(args)
assert not args
def repro_get_args(options, mod, load_args):
mod, args = repro_common(options, mod, load_args)
return mod, args
def repro_run(options, mod, load_args):
from torch._inductor.compile_fx import compile_fx_inner
mod, args = repro_common(options, mod, load_args)
from torch.cuda import synchronize
compiled = compile_fx_inner(mod, args)
assert not isinstance(compiled, str)
if options.accuracy != "":
# We don't really respect --accuracy vs --strict-accuracy here, it
# seems counterintuitive
if not same_two_models(
mod,
compiled,
args,
only_fwd=True,
ignore_non_fp=config.repro_ignore_non_fp,
):
raise AccuracyError("Bad accuracy detected")
else:
need_sync = False
for arg in args:
if isinstance(arg, torch.Tensor) and arg.is_cuda:
need_sync = True
break
compiled(list(args))
if need_sync:
synchronize() # ensure segfaults are surfaced
# TODO: lazily load the inputs or something, rather than cloning them
def run_repro(
mod,
load_args,
*,
command="run",
accuracy: Union[bool, str] = "",
save_dir=None,
tracing_mode=None,
patch_code=None,
check_str=None,
**kwargs,
):
for k in kwargs:
log.warning(
"Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch",
k,
)
if accuracy is True:
accuracy = "accuracy"
elif accuracy is False:
accuracy = ""
if patch_code is not None:
log.warning(
"patch_code no longer works on this version of PyTorch, silently ignoring"
)
parser = argparse.ArgumentParser(
description=f"""\
An after_aot repro script, typically triggering a bug in PyTorch Inductor.
When run with no arguments, this script defaults to running '{command}'.
Extra flags may be available; to find out more, try '{command} --help'.
There are also alternate subcommands available, see below.
default settings on this script:
{accuracy=}
{tracing_mode=}
{save_dir=}
{check_str=}
""",
formatter_class=argparse.RawTextHelpFormatter,
)
def common_flags(parser):
accuracy_group = parser.add_mutually_exclusive_group()
accuracy_group.add_argument(
"--no-accuracy",
dest="accuracy",
action="store_const",
const="",
default=accuracy,
help="do not test accuracy, just run the module and see if it errors",
)
accuracy_group.add_argument(
"--accuracy",
action="store_const",
const="accuracy",
default=accuracy,
help="""\
test if the RMSE between the compiled module and the fp64 reference is greater
than eager and the fp64 reference. This is usually more reliable than the
standard allclose test, as we expect numeric differences from compiling, often
improving accuracy over eager. RMSE test allows for compiled module to
diverge greatly from eager, as long as this divergence moves it closer to the
'true' mathematical value of the network. Caveats: (1) double precision can
still suffer from rounding error, so it is not a perfect reference (see for
example 'Herbie: Automatically Improving Floating Point Accuracy') for
approaches that detect the necessary working precision and compute it in
arbitrary precision floating point; unfortunately, this is not practical for
tensor computation; (2) if there are not enough samples in the output being
compared, we may get unlucky and have an unlucky greater RMSE than eager; this
could be overcome by applying a more rigorous statistical test at some
p-value, which we leave for future work.
""",
)
accuracy_group.add_argument(
"--strict-accuracy",
dest="accuracy",
action="store_const",
const="strict_accuracy",
default=accuracy,
help="""\
by default, when doing accuracy minification we will reject reductions which
change the divergence from a floating point divergence to a integral/boolean
divergence. This is because some operations like ReLU involve temporarily
sharp boundaries that smooth out again afterwards; without requiring
divergence on floating point, the minifier will often fixate on divergent
boolean tensor even though this is not the true source of the divergence.
However, rejecting these reductions makes it more difficult for the minifier
to make process. Using this option will let the minifier progress for ALL
divergences--you just might not end up with a useful repro in the end.""",
)
parser.add_argument(
"--save-dir",
type=str,
default=save_dir,
metavar="DIR",
help="directory where saved inputs live",
)
parser.add_argument(
"--no-save-dir",
dest="save_dir",
action="store_const",
const=None,
help="don't use any directory for saved inputs",
)
parser.add_argument(
"--tracing-mode",
type=str,
metavar="{real,fake,symbolic}",
default=tracing_mode,
help="how to trace the repro module into a GraphModule with metadata",
)
subparsers = parser.add_subparsers(
dest="command", metavar="{run,minify,analyze}", required=True
)
parser_run = subparsers.add_parser(
"run",
help="just run the repro",
)
common_flags(parser_run)
parser_minify = subparsers.add_parser(
"minify", help="run the minifier on the repro"
)
common_flags(parser_minify)
parser_get_args = subparsers.add_parser("get_args", help="get the args")
common_flags(parser_get_args)
parser_minify_isolate = parser_minify.add_mutually_exclusive_group()
parser_minify_isolate.add_argument(
"--isolate",
action="store_true",
default=True,
help="run in separate processes to avoid interference (default)",
)
parser_minify_isolate.add_argument(
"--no-isolate",
dest="isolate",
action="store_false",
help="speed up by running all compilation in same process",
)
parser_minify.add_argument(
"--skip-saving-eager-intermediates",
action="store_true",
help="skip saving eager intermediates on --minify",
)
# TODO: make this an option for --analyze too
parser_minify.add_argument(
"--offload-to-disk",
action="store_true",
help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing",
)
parser_minify.add_argument(
"--skip-sanity",
action="store_true",
help="skip sanity check at beginning of minification on original graph",
)
parser_minify.add_argument(
"--max-granularity",
type=int,
default=None,
help="start at this granularity and work down; must be power of 2",
)
parser_minify.add_argument(
"--check-str",
type=str,
default=check_str,
help="require minified program to fail with error containing this string",
)
parser_analyze = subparsers.add_parser(
"analyze", help="run the accuracy analyzer on the repro"
)
common_flags(parser_analyze)
parser_analyze.add_argument(
"--skip-saving-inductor-intermediates",
action="store_true",
help="skip saving inductor intermediates on --analyze",
)
parser_analyze.add_argument(
"--skip-saving-float64-intermediates",
action="store_true",
help="skip saving float64 intermediates",
)
parser_analyze.add_argument(
"--skip-check-deterministic",
action="store_true",
help="skip checking that the network is deterministic",
)
parser_analyze.add_argument(
"--stable-hash",
action="store_true",
help="use SHA-1 checksum instead of fast (but possibly unsound) hash",
)
# Run the repro in the context of minification, inverting exit code meaning
parser_minifier_query = subparsers.add_parser(
"minifier-query",
)
common_flags(parser_minifier_query)
parser_minifier_query.add_argument(
"--check-str",
type=str,
default=check_str,
help="require minified program to fail with error containing this string",
)
args = None
if len(sys.argv) <= 1:
args = [command, *sys.argv[1:]]
options = parser.parse_args(args)
COMMAND_FNS = {
"minify": repro_minify,
"analyze": repro_analyze,
"minifier-query": repro_minifier_query,
"run": repro_run,
"get_args": repro_get_args,
}
return COMMAND_FNS[options.command](options, mod, load_args)
|