fuzzer.py 37 KB

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