fuzzer.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. import importlib
  2. import itertools
  3. import logging
  4. import pickle
  5. import random
  6. import signal
  7. import string
  8. import traceback
  9. import types
  10. from collections.abc import Callable, KeysView, Sequence
  11. from enum import Enum
  12. from functools import partial, wraps
  13. from types import FrameType
  14. from typing import Any, get_args, get_origin, Literal, Optional, TypeVar, Union
  15. import torch
  16. from functorch.compile import min_cut_rematerialization_partition
  17. from torch._inductor.custom_graph_pass import CustomGraphPass, CustomPartitionerFn
  18. from torch._inductor.scheduler import BaseSchedulerNode
  19. from torch.utils._config_module import _ConfigEntry, ConfigModule
  20. from torch.utils._ordered_set import OrderedSet
  21. log = logging.getLogger(__name__)
  22. def is_type(type_hint, comp_type) -> bool: # type: ignore[no-untyped-def]
  23. """
  24. Determines if type_hint is comp_type. There are some type annotations that this doesn't work for.
  25. I think it's because some Type annotations are Type Objects and some are Special Forms, but not sure.
  26. There's definite room for improvement to make this more general for someone who deeply understands
  27. Python types.
  28. """
  29. return type_hint is comp_type or get_origin(type_hint) is comp_type
  30. def is_optional_type(type_hint) -> bool: # type: ignore[no-untyped-def]
  31. """
  32. Special case of is_type.
  33. """
  34. origin = get_origin(type_hint)
  35. if origin is Union:
  36. args = get_args(type_hint)
  37. return type(None) in args
  38. return False
  39. def is_callable_type(type_hint) -> bool: # type: ignore[no-untyped-def]
  40. """
  41. Special Case of is_type.
  42. """
  43. return type_hint.__name__ == "Callable"
  44. class DummyPass(CustomGraphPass):
  45. """
  46. A Dummy pass to be used by ConfigFuzzer
  47. """
  48. def __call__(self, graph: torch.fx.graph.Graph) -> None:
  49. return None
  50. def uuid(self) -> Optional[Any]:
  51. return None
  52. class DummyPartitionerFn(CustomPartitionerFn):
  53. """
  54. A Dummy partitioner function to be used by ConfigFuzzer
  55. """
  56. def __call__(
  57. self, gm: torch.fx.GraphModule, joint_inputs: Sequence[object], **kwargs: Any
  58. ) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule]:
  59. return min_cut_rematerialization_partition(gm, joint_inputs, **kwargs)
  60. def uuid(self) -> Optional[Any]:
  61. return None
  62. T = TypeVar("T")
  63. class TypeExemplars:
  64. """
  65. This class returns examples of a Type, given its class name.
  66. """
  67. TYPE_EXEMPLARS: dict[str, Any] = {
  68. CustomGraphPass.__name__: DummyPass(),
  69. CustomPartitionerFn.__name__: DummyPartitionerFn(),
  70. torch.fx.graph.Graph.__name__: torch.fx.graph.Graph(),
  71. BaseSchedulerNode.__name__: BaseSchedulerNode(None), # type: ignore[arg-type]
  72. }
  73. @staticmethod
  74. def example(t: type[T]) -> Optional[T]:
  75. """
  76. Return an example of a class.
  77. """
  78. return TypeExemplars.TYPE_EXEMPLARS.get(t.__name__, None)
  79. @staticmethod
  80. def contains(t: type[T]) -> bool:
  81. return t.__name__ in TypeExemplars.TYPE_EXEMPLARS
  82. def check_halide_import() -> bool:
  83. """checks if we have halide available"""
  84. try:
  85. importlib.import_module("halide")
  86. return True
  87. except ModuleNotFoundError:
  88. return False
  89. if check_halide_import():
  90. CUDA_BACKEND = ["triton", "halide"]
  91. else:
  92. CUDA_BACKEND = ["triton"]
  93. class Status(Enum):
  94. """
  95. The Status return value enum for Config Fuzzer
  96. """
  97. # ConfigFuzzer skipped the test
  98. SKIPPED = "skipped"
  99. # ConfigFuzzer compiled and ran the test and function it passed.
  100. PASSED = "passed"
  101. # ConfigFuzzer failed to compile the test function
  102. FAILED_COMPILE = "failed_compile"
  103. # ConfigFuzzer compiled the test function and running it raised an exception
  104. FAILED_RUN_COMPILE_EXCEPTION = "failed_run_compile_exception"
  105. # ConfigFuzzer ran eager and it raised an exception
  106. FAILED_RUN_EAGER_EXCEPTION = "failed_run_eager_exception"
  107. # ConfigFuzzer compiled the test function, but the return value indicated that the compiled value didn't match the
  108. # value from eager (or however else you set up the comparison in the test function)
  109. FAILED_RUN_RETURN = "failed_run_return"
  110. def failing(self) -> bool:
  111. """
  112. Convenience method to check whether these status represent failure.
  113. """
  114. return (
  115. self == Status.FAILED_COMPILE
  116. or self == Status.FAILED_RUN_EAGER_EXCEPTION
  117. or self == Status.FAILED_RUN_COMPILE_EXCEPTION
  118. or self == Status.FAILED_RUN_RETURN
  119. )
  120. # Sometime the types of configs aren't expressive enough to be captured by python type system, so the options can be
  121. # manually specified here:
  122. # TODO this needs to be indexed to the module, like inductor or dynamo, for name collisions
  123. TYPE_OVERRIDES: dict[str, list[Any]] = {
  124. "cuda_backend": CUDA_BACKEND,
  125. "post_grad_fusion_options": [
  126. {
  127. "batch_linear_post_grad": {
  128. "shape_broadcast_batch_linear": True,
  129. "fuse_nodes_with_same_users": True,
  130. },
  131. "batch_aten_mul": {"fuse_nodes_with_same_parent": False},
  132. "batch_aten_sigmoid": {"fuse_nodes_with_same_parent": True},
  133. "batch_aten_add": {"fuse_nodes_with_same_parent": True},
  134. "normalization_aten_pass": {},
  135. "unbind_stack_aten_pass": {},
  136. },
  137. {
  138. "batch_aten_add": {},
  139. "batch_aten_mul": {},
  140. "batch_aten_sub": {},
  141. "batch_aten_div": {},
  142. "group_linear": {"require_fbgemm": True},
  143. },
  144. ],
  145. "autoheuristic_collect": ["pad_mm", "mixed_mm"],
  146. "autoheuristic_use": ["pad_mm", "mixed_mm"],
  147. "traceable_tensor_subclasses": [OrderedSet()],
  148. "nontraceable_tensor_subclasses": [OrderedSet()],
  149. }
  150. SamplingType = Callable[[str, type[Any], Any], Any]
  151. class SamplingMethod(Enum):
  152. """
  153. This class handles the process of assigning concrete values to type annotations. So a type annotation of
  154. ```python
  155. foo: Optional[int] = None
  156. ```
  157. Will be assigned an int if the dispatch function gets TOGGLE, or a 50/50 split between an int and None if it gets
  158. RANDOM.
  159. """
  160. TOGGLE = "TOGGLE" # toggle to the opposite value
  161. RANDOM = "RANDOM" # randomly choose an option
  162. @staticmethod
  163. def _generate_value_for_type(
  164. random_sample: bool, field_name: str, type_hint: type[Any], default: Any
  165. ) -> Any:
  166. """
  167. Generates a value of a type based on the setting.
  168. """
  169. # look for name in type overrides
  170. if field_name in TYPE_OVERRIDES:
  171. return random.choice(TYPE_OVERRIDES[field_name])
  172. if type_hint is bool:
  173. return random.choice([True, False]) if random_sample else not default
  174. elif type_hint is int:
  175. # NOTE initially tried to use negation of the value, but it doesn't work because most types are ints
  176. # when they should be natural numbers + zero. Python types to cover these values aren't super convenient.
  177. return random.randint(0, 1000)
  178. elif type_hint is float:
  179. return random.uniform(0, 1000)
  180. elif type_hint is str:
  181. characters = string.ascii_letters + string.digits + string.punctuation
  182. return "".join(
  183. random.choice(characters) for _ in range(random.randint(1, 20))
  184. )
  185. elif is_type(type_hint, list):
  186. elem_type = getattr(
  187. type_hint,
  188. "__args__",
  189. [type(default[0])] if default and len(default) else [type(None)],
  190. )[0]
  191. new_default = default[0] if default and len(default) > 0 else None
  192. return [
  193. SamplingMethod._generate_value_for_type(
  194. random_sample, field_name, elem_type, new_default
  195. )
  196. for _ in range(random.randint(1, 3))
  197. ]
  198. elif is_type(type_hint, set): # noqa: set_linter
  199. indexable = list(default)
  200. elem_type = getattr(
  201. type_hint,
  202. "__args__",
  203. [type(indexable[0])] if default and len(default) else [type(None)],
  204. )[0]
  205. new_default = indexable[0] if default and len(default) > 0 else None
  206. return { # noqa: set_linter
  207. SamplingMethod._generate_value_for_type(
  208. random_sample, field_name, elem_type, new_default
  209. )
  210. for _ in range(random.randint(1, 3))
  211. }
  212. elif is_type(type_hint, OrderedSet):
  213. indexable = list(default)
  214. elem_type = getattr(
  215. type_hint,
  216. "__args__",
  217. [type(indexable[0])] if default and len(default) else [type(None)],
  218. )[0]
  219. new_default = indexable[0] if default and len(default) > 0 else None
  220. return OrderedSet(
  221. [
  222. SamplingMethod._generate_value_for_type(
  223. random_sample, field_name, elem_type, new_default
  224. )
  225. for _ in range(random.randint(1, 3))
  226. ]
  227. )
  228. elif is_type(type_hint, dict):
  229. key_type, value_type = getattr(
  230. type_hint,
  231. "__args__",
  232. map(type, next(iter(default.items())))
  233. if (default is not None and len(default))
  234. else (type(None), type(None)),
  235. )
  236. if default is not None and len(default.items()) > 0:
  237. default_key, default_val = next(iter(default.items()))
  238. else:
  239. default_key, default_val = None, None
  240. return {
  241. SamplingMethod._generate_value_for_type(
  242. random_sample, field_name, key_type, default_key
  243. ): SamplingMethod._generate_value_for_type(
  244. random_sample, field_name, value_type, default_val
  245. )
  246. for _ in range(random.randint(0, 3))
  247. }
  248. elif is_type(type_hint, Union) or is_type(type_hint, types.UnionType):
  249. # do whatever is not the type of default
  250. try:
  251. assert len(type_hint.__args__) > 1
  252. except AttributeError as err:
  253. raise ValueError("Union type with no args") from err
  254. if random_sample:
  255. new_type = random.choice(type_hint.__args__)
  256. else:
  257. new_type = random.choice(
  258. [t for t in type_hint.__args__ if t is not type(default)]
  259. )
  260. try:
  261. new_default = new_type()
  262. except Exception:
  263. # if default constructor doesn't work, try None
  264. new_default = None
  265. return SamplingMethod._generate_value_for_type(
  266. random_sample, field_name, new_type, new_default
  267. )
  268. elif is_type(type_hint, tuple):
  269. args = getattr(
  270. type_hint,
  271. "__args__",
  272. tuple(map(type, default)),
  273. )
  274. zipped = zip(args, default)
  275. return tuple(
  276. map( # noqa: C417
  277. lambda x: SamplingMethod._generate_value_for_type(
  278. random_sample, field_name, x[0], x[1]
  279. ),
  280. zipped,
  281. )
  282. )
  283. elif is_type(type_hint, Literal):
  284. try:
  285. if random_sample:
  286. return random.choice(type_hint.__args__)
  287. else:
  288. choices = [t for t in type_hint.__args__ if t != default]
  289. if choices:
  290. return random.choice(choices)
  291. else:
  292. return default
  293. except AttributeError as err:
  294. raise ValueError("Literal type with no args") from err
  295. elif is_optional_type(type_hint):
  296. try:
  297. elem_type = type_hint.__args__[0]
  298. except AttributeError as err:
  299. raise ValueError("Optional type with no args") from err
  300. if random_sample:
  301. return random.choice(
  302. [
  303. None,
  304. SamplingMethod._generate_value_for_type(
  305. random_sample, field_name, elem_type, default
  306. ),
  307. ]
  308. )
  309. else:
  310. if default is None:
  311. return SamplingMethod._generate_value_for_type(
  312. random_sample, field_name, elem_type, None
  313. )
  314. else:
  315. return None
  316. elif type_hint is type(None):
  317. return None
  318. elif is_callable_type(type_hint):
  319. try:
  320. return_type = list(type_hint.__args__)[-1]
  321. except AttributeError as err:
  322. raise ValueError("Callable type with no args") from err
  323. @wraps(lambda *args, **kwargs: None)
  324. def dummy_function(*args, **kwargs): # type: ignore[no-untyped-def]
  325. return SamplingMethod._generate_value_for_type(
  326. random_sample, field_name, return_type, None
  327. )
  328. return dummy_function
  329. elif type_hint == torch._ops.OpOverload:
  330. return torch.ops.aten.add.default
  331. elif TypeExemplars.contains(type_hint):
  332. return TypeExemplars.example(type_hint)
  333. elif type_hint == Any:
  334. return 1 if default != 1 else 2
  335. else:
  336. raise ValueError(f"Unable to process type {type_hint}. PRs welcome :)")
  337. @staticmethod
  338. def dispatch(sm: "SamplingMethod") -> SamplingType:
  339. """
  340. Returns a function that will generate values from a type, based on the SamplingMethod passed in.
  341. """
  342. if sm == SamplingMethod.RANDOM:
  343. return partial(SamplingMethod._generate_value_for_type, True)
  344. elif sm == SamplingMethod.TOGGLE:
  345. return partial(SamplingMethod._generate_value_for_type, False)
  346. else:
  347. raise ValueError(f"malformed sampling method: {sm}")
  348. class Default:
  349. """
  350. Singleton default object that will cause the ConfigFuzzer to always use the default value set in the config.
  351. """
  352. DEFAULT = Default()
  353. # The combination of config settings being set (based on their strings)
  354. ComboType = tuple[str, ...]
  355. class ResultType:
  356. """
  357. The mapping of the combo strings to the result status after running the config fuzzer.
  358. """
  359. _vals: dict[ComboType, Status]
  360. def __repr__(self) -> str:
  361. return f"ResultType[{self._vals}]"
  362. def __init__(self) -> None:
  363. self._vals = {}
  364. def __len__(self) -> int:
  365. return len(self._vals)
  366. def num_ran(self) -> int:
  367. """
  368. Returns how many combos actually ran (weren't skipped).
  369. """
  370. ret = len(self._vals)
  371. for status in self._vals.values():
  372. if status == Status.SKIPPED:
  373. ret -= 1
  374. return ret
  375. def set(self, combo: ComboType, status: Status) -> None:
  376. combo = tuple(sorted(combo))
  377. self._vals[combo] = status
  378. def lookup(self, combo: ComboType) -> Optional[Status]:
  379. combo = tuple(sorted(combo))
  380. return self._vals.get(combo, None)
  381. def keys(self) -> KeysView[ComboType]:
  382. return self._vals.keys()
  383. # Type that maps config strings to their default value
  384. ConfigType = dict[str, Any]
  385. # Callable that returns a bool
  386. FactoryOutputType = Callable[[], bool]
  387. # input function factory
  388. FactoryType = Callable[[], FactoryOutputType]
  389. # Why are some configs disabled by default? Because if we don't the fuzzer produces uninteresting results.
  390. # It will always hone-in on these failures, even with the most basic model, making it useless for
  391. # debugging more complex models.
  392. #
  393. # More explicit explanations are below:
  394. # Out of Scope: We can't fuzz, say, the cuda version because that comes from the environment and will
  395. # produce a failure if not aligned with env.
  396. # Known Failure: Disabled due to known failure. Hopefully re-enable. Known failures are listed in the
  397. # docstring of this file.
  398. # Required: Required for the fuzzer to operate (removing caching, etc.)
  399. # FSDP: Flag meant for FSDP that fails in non FSDP envs. Re-enable these if you're testing FSDP.
  400. # Typing: disabled because the type annotation of the config isn't constrained enough to produce
  401. # meaningful fuzz values. These could be improved.
  402. # Timing: These take too long to compile, feel free to enable.
  403. MODULE_DEFAULTS: dict[str, ConfigType] = {
  404. "torch._inductor.config": {
  405. "force_disable_caches": True, # Required
  406. "cpp.cxx": DEFAULT, # Out of Scope
  407. "TYPE_CHECKING": DEFAULT, # Not a config
  408. "max_autotune_pointwise": DEFAULT, # Timing
  409. "max_autotune_gemm": DEFAULT, # Timing, re-enable when autotune speed improvements merged.
  410. "max_autotune_gemm_backends": DEFAULT, # Timing
  411. "max_autotune_conv_backends": DEFAULT, # Timing
  412. "max_autotune_gemm_search_space": DEFAULT, # Timing
  413. "max_autotune_subproc_result_timeout_seconds": DEFAULT, # Timing
  414. "max_autotune_subproc_graceful_timeout_seconds": DEFAULT, # Timing
  415. "max_autotune_subproc_terminate_timeout_seconds": DEFAULT, # Timing
  416. "aot_inductor.presets": DEFAULT, # Typing
  417. "cuda.arch": DEFAULT, # Out of Scope
  418. "cuda.version": DEFAULT, # Out of Scope
  419. "cuda.cutlass_dir": DEFAULT, # Out of Scope
  420. "cuda.cuda_cxx": DEFAULT, # Out of Scope
  421. "rocm.arch": DEFAULT, # Out of Scope
  422. "rocm.ck_supported_arch": DEFAULT, # Out of Scope
  423. "rocm.ck_dir": DEFAULT, # Out of Scope
  424. "rocm.rocm_home": DEFAULT, # Out of Scope
  425. "check_stack_no_cycles_TESTING_ONLY": DEFAULT, # Testing
  426. "sleep_sec_TESTING_ONLY": DEFAULT, # Testing
  427. "triton.inject_relu_bug_TESTING_ONLY": DEFAULT, # Testing
  428. "reorder_for_compute_comm_overlap": DEFAULT, # FSDP
  429. "enabled_metric_tables": DEFAULT, # Typing
  430. "triton.debug_sync_graph": DEFAULT, # Known Failure
  431. "triton.debug_sync_kernel": DEFAULT, # Known Failure
  432. "profile_bandwidth_regex": DEFAULT, # Known Failure
  433. "disable_cpp_codegen": DEFAULT, # Known Failure
  434. "trace.save_real_tensors": DEFAULT, # Known Failure
  435. "pre_grad_fusion_options": DEFAULT, # Typing
  436. "external_matmul": DEFAULT, # Typing, need to add this to type overrides or type exemplars.
  437. "test_configs.autotune_choice_name_regex": DEFAULT, # Typing
  438. "test_configs.autotune_choice_desc_regex": DEFAULT, # Typing
  439. "cpp.enable_floating_point_contract_flag": DEFAULT, # Typing
  440. "post_grad_custom_pre_pass": DEFAULT, # Typing
  441. "post_grad_custom_post_pass": DEFAULT, # Typing
  442. "reorder_for_compute_comm_overlap_passes": DEFAULT, # Typing
  443. "joint_custom_post_pass": DEFAULT, # Typing
  444. "joint_custom_pre_pass": DEFAULT, # Typing
  445. "pre_grad_custom_pass": DEFAULT, # Typing
  446. "custom_partitioner_fn": DEFAULT, # Typing
  447. "inductor_choices_class": DEFAULT, # Typing
  448. },
  449. "torch._dynamo.config": {
  450. "traceable_tensor_subclasses": DEFAULT, # Typing
  451. "nontraceable_tensor_subclasses": DEFAULT, # Typing
  452. "compiled_autograd_kwargs_override": DEFAULT, # Typing
  453. "fail_on_recompile_limit_hit": DEFAULT, # fails in combo with suppress_errors
  454. "suppress_errors": DEFAULT,
  455. "caching_precompile": False, # Required
  456. },
  457. }
  458. class ConfigFuzzer:
  459. """
  460. This tool makes it easy to search through config state-space with a minimal reproduction or test, either for
  461. debugging or just bug hunting.
  462. It has two entry points:
  463. - bisect, which randomly flips configs and tries to find the minimal reproduction upon failure.
  464. - fuzz_n_tuple, which tries every combination of n configs. This grows quickly as a function of n, so beware.
  465. bisect is recommended, but fuzz_n_tuple can give you peace of mind that a new config will compose with
  466. every other config.
  467. The main interface is a function factory that will return Callables to be torch.compiled. This function factory
  468. should return a test function when it's called. Said test function returns a boolean, which determines whether
  469. the ConfigFuzzer considers it a successful run or not. Throwing an exception from within the function will be
  470. considered a failure as well.
  471. # Example usage:
  472. ```python
  473. import torch._inductor.config as cfg
  474. def create_simple_test_model_gpu() -> FactoryOutputType:
  475. batch_size = 32
  476. seq_length = 50
  477. hidden_size = 768
  478. def test_fn() -> bool:
  479. inp = torch.randn(batch_size, seq_length, hidden_size, device="cuda")
  480. weight = torch.randn(hidden_size, hidden_size, device="cuda")
  481. matmul_output = inp @ weight
  482. final_output = torch.nn.LayerNorm(hidden_size, device="cuda")(matmul_output)
  483. return True
  484. return test_fn
  485. fuzzer = ConfigFuzzer(cfg, create_simple_test_model_gpu, seed=2)
  486. # Test every pair of configs:
  487. results = fuzzer.fuzz_n_tuple(n, max_combinations=10000000)
  488. visualize_results(n, results)
  489. # Test random configs with bisection:
  490. ret = fuzzer.bisect(num_attempts=10)
  491. # reproduce a failing config
  492. fuzzer.reproduce(
  493. [{"triton.autotune_pointwise": ..., "coordinate_descent_tuning": ...}]
  494. )
  495. ```
  496. The list of known failures on inductor config are:
  497. cpp_wrapper, triton_debug_sync_graph
  498. cpp_wrapper, triton_debug_sync_kernel
  499. cpp_wrapper, disable_cpp_codegen
  500. combo_kernels, benchmark_combo_kernel, profile_bandwidth, profile_bandwidth_regex
  501. trace.enabled, trace.save_real_tensors
  502. """
  503. sample: SamplingType
  504. default: ConfigType
  505. def __init__(
  506. self,
  507. config_module: ConfigModule,
  508. test_model_fn_factory: FactoryType,
  509. seed: int,
  510. default: Optional[ConfigType] = None,
  511. sm: SamplingMethod = SamplingMethod.TOGGLE,
  512. test_timeout: int = 3600,
  513. ):
  514. """
  515. Args:
  516. config_module: The module containing the configs to fuzz
  517. test_model_fn_factory: Function that returns a test model, which runs and returns True if successful, or
  518. the outputs if they should be compared with eager
  519. seed: Randomness seed.
  520. default: Default values for the config. Inductor has preset based on know failures.
  521. sm: How type value samples are generated, default TOGGLE.
  522. test_timeout: max time a test can take.
  523. """
  524. self.seed = seed
  525. self.test_timeout = test_timeout
  526. self.detailed_results: dict[ComboType, dict[str, Any]] = {}
  527. self.config_module = config_module
  528. self.test_model_fn_factory = test_model_fn_factory
  529. self.fields: dict[str, _ConfigEntry] = self.config_module._config
  530. self.sample = SamplingMethod.dispatch(sm)
  531. if default is None:
  532. if self.config_module.__name__ in MODULE_DEFAULTS:
  533. self.default = MODULE_DEFAULTS[self.config_module.__name__]
  534. else:
  535. raise ValueError("No default passed to ConfigFuzzer.")
  536. else:
  537. self.default = default
  538. def __repr__(self) -> str:
  539. return (
  540. f"ConfigFuzzer(config_module={self.config_module}, "
  541. f"test_model_fn_factor={self.test_model_fn_factory}, seed={self.seed}, default={self.default})"
  542. )
  543. def _set_config(self, field_name: str, value: Any) -> None:
  544. """Set a config value in the module."""
  545. setattr(self.config_module, field_name, value)
  546. def _reset_configs(self) -> None:
  547. """Reset all configs to their default values."""
  548. for field_name, field_obj in self.fields.items():
  549. self._set_config(field_name, field_obj.default)
  550. def new_config(self) -> ConfigType:
  551. """creates a new config from the default"""
  552. ret = {
  553. name: val if val != DEFAULT else self.fields[name].default
  554. for name, val in self.default.items()
  555. }
  556. return ret
  557. def reproduce(self, configs: Sequence[ConfigType]) -> ResultType:
  558. """entrypoint to reproduce any failure"""
  559. results = ResultType()
  560. for conf in configs:
  561. self._reproduce_single_helper(conf, results)
  562. return results
  563. def _reproduce_single_helper(self, conf: ConfigType, results: ResultType) -> None:
  564. print(f"Starting repro of {conf}")
  565. new_config = self.new_config()
  566. new_config.update(conf)
  567. self.test_config(results, new_config)
  568. print(f"Status of {conf}:\n{results.lookup(tuple(conf.keys()))}")
  569. def reproduce_single(self, config: ConfigType) -> ResultType:
  570. results = ResultType()
  571. self._reproduce_single_helper(config, results)
  572. return results
  573. def _fuzz_helper(self, results: ResultType, combo: ComboType) -> Status:
  574. print(combo)
  575. if st := results.lookup(combo):
  576. # we already processed this config
  577. return st
  578. config = self.new_config()
  579. skip = False
  580. for field_name in combo:
  581. if field_name in config:
  582. # don't break here because we need to build the config dict
  583. skip = True
  584. if field_name.startswith("_"):
  585. skip = True
  586. field = self.fields[field_name]
  587. value = self.sample(field_name, field.value_type, field.default)
  588. config[field_name] = value
  589. if skip:
  590. results.set(combo, Status.SKIPPED)
  591. return Status.SKIPPED
  592. return self.test_config(results, config)
  593. def fuzz_n_tuple(self, n: int, max_combinations: int = 1000) -> ResultType:
  594. """
  595. Test every combination of n configs.
  596. returns a dict of this shape: {(config-1, config-2... config-n): status}
  597. """
  598. results = ResultType()
  599. print(f"Starting {n}-tuple testing with seed {self.seed}")
  600. random.seed(self.seed)
  601. for combo in itertools.combinations(self.fields, n):
  602. st = self._fuzz_helper(results, combo)
  603. if st != Status.SKIPPED:
  604. max_combinations -= 1
  605. if max_combinations <= 0:
  606. print("Reached maximum combinations limit")
  607. break
  608. return results
  609. def save_state(self, filename: str = "fuzzer_state.pkl") -> None:
  610. """Save the current fuzzer state to a file"""
  611. with open(filename, "wb") as f:
  612. pickle.dump(
  613. {"results": self.results, "detailed_results": self.detailed_results}, f
  614. )
  615. def load_state(self, filename: str = "fuzzer_state.pkl") -> None:
  616. """Load fuzzer state from a file"""
  617. with open(filename, "rb") as f:
  618. state = pickle.load(f)
  619. self.results = state["results"]
  620. self.detailed_results = state.get("detailed_results", {})
  621. def timeout_handler(self, signum: int, frame: Optional[FrameType]) -> None:
  622. raise TimeoutError("Test execution timed out")
  623. def test_config(self, results: ResultType, config: ConfigType) -> Status:
  624. """
  625. Tests a config by calling the function produced by the factory function.
  626. """
  627. original_handler = signal.signal(signal.SIGALRM, self.timeout_handler)
  628. signal.alarm(self.test_timeout)
  629. print(f"Testing config {config}")
  630. config_tuple = tuple(config.keys())
  631. if ret := results.lookup(config_tuple):
  632. signal.signal(signal.SIGALRM, original_handler)
  633. return ret
  634. def print_config() -> None:
  635. for field, value in config.items():
  636. print(f"{field} = {value}")
  637. def get_error_info(exc: Exception) -> dict[str, Any]:
  638. return {
  639. "exception": str(exc),
  640. "traceback": traceback.format_exc(),
  641. "config": config.copy(),
  642. }
  643. def handle_return(
  644. message: str,
  645. return_status: Status,
  646. print_traceback: bool,
  647. exc: Optional[Exception],
  648. ) -> Status:
  649. signal.signal(signal.SIGALRM, original_handler)
  650. print(f"{message} with config combination:")
  651. print_config()
  652. if exc:
  653. self.detailed_results[config_tuple] = get_error_info(exc)
  654. if print_traceback:
  655. traceback.print_exc()
  656. results.set(config_tuple, return_status)
  657. return return_status
  658. # reset config
  659. torch._dynamo.reset()
  660. self._reset_configs()
  661. for name, value in config.items():
  662. self._set_config(name, value)
  663. # try running eager
  664. test_model_fn = self.test_model_fn_factory()
  665. try:
  666. test_model_fn()
  667. except Exception as exc:
  668. return handle_return(
  669. "Eager exception", Status.FAILED_RUN_EAGER_EXCEPTION, True, exc
  670. )
  671. # try compilation
  672. try:
  673. test_model_fn2 = self.test_model_fn_factory()
  674. comp = torch.compile(test_model_fn2, backend="inductor")
  675. except Exception as exc:
  676. return handle_return(
  677. "Exception compiling", Status.FAILED_COMPILE, True, exc
  678. )
  679. # try running compiled
  680. try:
  681. compile_result = comp()
  682. except Exception as exc:
  683. return handle_return(
  684. "Exception running compiled",
  685. Status.FAILED_RUN_COMPILE_EXCEPTION,
  686. True,
  687. exc,
  688. )
  689. # bool return value means don't compare with eager
  690. if not compile_result:
  691. return handle_return(
  692. "Function returned False", Status.FAILED_RUN_RETURN, False, None
  693. )
  694. else:
  695. return handle_return("Function succeeded", Status.PASSED, False, None)
  696. def bisect(self, num_attempts: int = 100, p: float = 0.5) -> list[ConfigType]:
  697. """
  698. Test configs and bisect to minimal failing configuration.
  699. """
  700. print(f"Starting random testing with bisection, seed {self.seed}, and p {p}")
  701. random.seed(self.seed)
  702. self._reset_configs()
  703. results = ResultType()
  704. ret: list[ConfigType] = []
  705. for attempt in range(num_attempts):
  706. print(f"Random attempt {attempt + 1}/{num_attempts}")
  707. config = self.new_config()
  708. for field_name, config_entry in self.fields.items():
  709. if (
  710. field_name not in config
  711. and not field_name.startswith("_")
  712. and "TESTING_ONLY" not in field_name
  713. and random.random() < p
  714. ):
  715. value = self.sample(
  716. field_name, config_entry.value_type, config_entry.default
  717. )
  718. config[field_name] = value
  719. status = self.test_config(results, config)
  720. if status not in OrderedSet([Status.PASSED, Status.SKIPPED]):
  721. if minimal_failing_config := self._bisect_failing_config(
  722. results, config
  723. ):
  724. print(f"Minimum failing config: {minimal_failing_config}")
  725. ret.append(minimal_failing_config)
  726. return ret
  727. def _bisect_failing_config(
  728. self, results: ResultType, failing_config: ConfigType
  729. ) -> Optional[ConfigType]:
  730. return self._bisect_failing_config_helper(results, list(failing_config.items()))
  731. def _bisect_failing_config_helper(
  732. self, results: ResultType, failing_config: list[tuple[str, Any]]
  733. ) -> Optional[ConfigType]:
  734. """
  735. Bisect a failing configuration to find minimal set of configs that cause failure.
  736. Splits it into halves, then fourths, then tries dropping configs one-by-one.
  737. """
  738. print(f"bisecting config: {failing_config}")
  739. if not failing_config:
  740. return None
  741. def test(x: list[tuple[str, Any]]) -> Status:
  742. d = dict(x)
  743. result = self.test_config(results, d)
  744. return result
  745. if len(failing_config) <= 1:
  746. return dict(failing_config) if test(failing_config).failing() else None
  747. random.shuffle(failing_config)
  748. mid = len(failing_config) // 2
  749. first_half = failing_config[:mid]
  750. second_half = failing_config[mid:]
  751. if test(first_half).failing():
  752. return self._bisect_failing_config_helper(results, first_half)
  753. if test(second_half).failing():
  754. return self._bisect_failing_config_helper(results, second_half)
  755. if len(failing_config) >= 8:
  756. low = len(failing_config) // 4
  757. high = mid + low
  758. quart1 = failing_config[low:]
  759. if test(quart1).failing():
  760. return self._bisect_failing_config_helper(results, quart1)
  761. quart2 = failing_config[:low] + second_half
  762. if test(quart2).failing():
  763. return self._bisect_failing_config_helper(results, quart2)
  764. quart3 = first_half + failing_config[:high]
  765. if test(quart3).failing():
  766. return self._bisect_failing_config_helper(results, quart3)
  767. quart4 = failing_config[high:]
  768. if test(quart4).failing():
  769. return self._bisect_failing_config_helper(results, quart4)
  770. # try dropping one value at a time
  771. for i in range(len(failing_config)):
  772. new_list = [x for j, x in enumerate(failing_config) if j != i]
  773. if test(new_list).failing():
  774. return self._bisect_failing_config_helper(results, new_list)
  775. # we have the minimal set
  776. return dict(failing_config)
  777. def visualize_results(
  778. n: int, results: ResultType, filename: str = "results.html"
  779. ) -> None:
  780. """
  781. Creates an HTML document representing the results of running the fuzzer with fuzz_n_tuple, with n = 2.
  782. """
  783. # TODO support more dimensions
  784. assert n == 2
  785. assert len(results) > 0
  786. input_set: OrderedSet[str] = OrderedSet({})
  787. for key in results.keys(): # noqa: SIM118
  788. input_set.add(key[0])
  789. input_set.add(key[1])
  790. input_list = sorted(input_set)
  791. # Start the HTML content
  792. html_content = """
  793. <!DOCTYPE html>
  794. <html lang="en">
  795. <head>
  796. <meta charset="UTF-8">
  797. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  798. <title> Fuzzer Visualization</title>
  799. <style>
  800. table {
  801. border-collapse: collapse;
  802. width: 50%;
  803. margin: 20px auto;
  804. }
  805. th, td {
  806. border: 1px solid #ddd;
  807. padding: 8px;
  808. text-align: center;
  809. }
  810. th {
  811. background-color: #f2f2f2;
  812. }
  813. .skipped {
  814. background-color: yellow;
  815. }
  816. .passed {
  817. background-color: green;
  818. color: white;
  819. }
  820. .failed {
  821. background-color: red;
  822. color: white;
  823. }
  824. </style>
  825. </head>
  826. <body>
  827. <h2 style="text-align: center;">Fuzzer Visualization</h2>
  828. <table>
  829. <thead>
  830. """
  831. html_content += "<tr><th>\\</th>"
  832. for col_name in input_list:
  833. col = "<br>".join(col_name)
  834. html_content += f"<th>{col}</th>"
  835. html_content += "</tr></thead><tbody>"
  836. # Add table rows
  837. for row_name in input_list:
  838. html_content += f"<tr><th>{row_name}</th>"
  839. for col_name in input_list:
  840. # Determine the status class for the cell
  841. status_enum = results.lookup((row_name, col_name))
  842. status_class = ""
  843. status_val = ""
  844. if status_enum == Status.SKIPPED:
  845. status_class = "skipped"
  846. status_val = "-"
  847. elif status_enum == Status.PASSED:
  848. status_class = "passed"
  849. status_val = "O"
  850. elif status_enum == Status.FAILED_RUN_EAGER_EXCEPTION:
  851. status_class = "failed"
  852. status_val = "e"
  853. elif status_enum == Status.FAILED_RUN_COMPILE_EXCEPTION:
  854. status_class = "failed"
  855. status_val = "E"
  856. elif status_enum == Status.FAILED_RUN_RETURN:
  857. status_class = "failed"
  858. status_val = "R"
  859. elif status_enum == Status.FAILED_COMPILE:
  860. status_class = "failed"
  861. status_val = "C"
  862. else:
  863. status_class = "skipped"
  864. status_val = "-"
  865. html_content += f'<td class="{status_class}">{status_val}</td>'
  866. html_content += "</tr>"
  867. html_content += """
  868. </tbody>
  869. </table>
  870. </body>
  871. </html>
  872. """
  873. with open(filename, "w") as file:
  874. file.write(html_content)