


"""simple docstring"""
def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE = False			)      ->			bool:
							if n == 2:
														return True
							if not n % 2 or n < 2:
														return False
							if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
														return False
							if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
														raise ValueError(
														    """Warning: upper bound of deterministic test is exceeded. """
														    """Pass allow_probable=True to allow probabilistic test. """
														    """A return value of True indicates a probable prime."""			)
							# array bounds provided by analysis
							snake_case_          =						[
							    2_047,
							    1_373_653,
							    25_326_001,
							    3_215_031_751,
							    2_152_302_898_747,
							    3_474_749_660_383,
							    341_550_071_728_321,
							    1,
							    3_825_123_056_546_413_051,
							    1,
							    1,
							    318_665_857_834_031_151_167_461,
							    3_317_044_064_679_887_385_961_981,
							]

							snake_case_          =						[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
							for idx, _p in enumerate(_SCREAMING_SNAKE_CASE			,	1			):
														if n < _p:
																					# then we have our last prime to check
																					snake_case_          =						primes[:idx]
																					break
							snake_case_    ,  snake_case_          =						n - 1, 0
							# break up n -1 into a power of 2 (s) and
							# remaining odd component
							# essentially, solve for d * 2 ** s == n - 1
							while d % 2 == 0:
														d //= 2
														s += 1
							for prime in plist:
														snake_case_          =						False
														for r in range(_SCREAMING_SNAKE_CASE			):
																					snake_case_          =						pow(_SCREAMING_SNAKE_CASE			,	d * 2**r			,	_SCREAMING_SNAKE_CASE			)
																					# see article for analysis explanation for m
																					if (r == 0 and m == 1) or ((m + 1) % n == 0):
																												snake_case_          =						True
																												# this loop will not determine compositeness
																												break
														if pr:
																					continue
														# if pr is False, then the above loop never evaluated to true,
														# and the n MUST be composite
														return False
							return True







def   _a			( )      ->			None:
							assert not miller_rabin(561			)
							assert miller_rabin(563			)
							# 2047

							assert not miller_rabin(838_201			)
							assert miller_rabin(838_207			)
							# 1_373_653

							assert not miller_rabin(17_316_001			)
							assert miller_rabin(17_316_017			)
							# 25_326_001

							assert not miller_rabin(3_078_386_641			)
							assert miller_rabin(3_078_386_653			)
							# 3_215_031_751

							assert not miller_rabin(1_713_045_574_801			)
							assert miller_rabin(1_713_045_574_819			)
							# 2_152_302_898_747

							assert not miller_rabin(2_779_799_728_307			)
							assert miller_rabin(2_779_799_728_327			)
							# 3_474_749_660_383

							assert not miller_rabin(113_850_023_909_441			)
							assert miller_rabin(113_850_023_909_527			)
							# 341_550_071_728_321

							assert not miller_rabin(1_275_041_018_848_804_351			)
							assert miller_rabin(1_275_041_018_848_804_391			)
							# 3_825_123_056_546_413_051

							assert not miller_rabin(79_666_464_458_507_787_791_867			)
							assert miller_rabin(79_666_464_458_507_787_791_951			)
							# 318_665_857_834_031_151_167_461

							assert not miller_rabin(552_840_677_446_647_897_660_333			)
							assert miller_rabin(552_840_677_446_647_897_660_359			)
							# 3_317_044_064_679_887_385_961_981
							# upper limit for probabilistic test


if __name__ == "__main__":
				test_miller_rabin()







"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock

import torch

from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config


# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)

__SCREAMING_SNAKE_CASE							:      Tuple						=      [
    'cross_validation.py',
    'gradient_accumulation.py',
    'local_sgd.py',
    'multi_process_metrics.py',
    'memory.py',
    'automatic_gradient_accumulation.py',
    'fsdp_with_peak_mem_tracking.py',
    'deepspeed_with_config_support.py',
    'megatron_lm_gpt_pretraining.py',
]





class        __A       (unittest.TestCase):





							'''simple docstring'''

							def 						lowerCAmelCase    (			self							: str						,    UpperCAmelCase_							: str						,    UpperCAmelCase_							: bool						,    UpperCAmelCase_							: str = None						,    UpperCAmelCase_							: list = None    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						None
														snake_case_          =						os.path.abspath(os.path.join("""examples"""						,    """by_feature"""    )    )
														snake_case_          =						os.path.abspath("""examples"""    )
														for item in os.listdir(UpperCAmelCase_    ):
																					if item not in EXCLUDE_EXAMPLES:
																												snake_case_          =						os.path.join(UpperCAmelCase_						,    UpperCAmelCase_    )
																												if os.path.isfile(UpperCAmelCase_    ) and ".py" in item_path:
																																			with self.subTest(
																																			    tested_script=UpperCAmelCase_						,    feature_script=UpperCAmelCase_						,    tested_section="""main()""" if parser_only else """training_function()"""						,    ):
																																										snake_case_          =						compare_against_test(
																																										    os.path.join(UpperCAmelCase_						,    UpperCAmelCase_    )						,    UpperCAmelCase_						,    UpperCAmelCase_						,    UpperCAmelCase_    )
																																										snake_case_          =						"""\n""".join(UpperCAmelCase_    )
																																										if special_strings is not None:
																																																	for string in special_strings:
																																																								snake_case_          =						diff.replace(UpperCAmelCase_						,    """"""    )
																																										self.assertEqual(UpperCAmelCase_						,    """"""    )



							def 						lowerCAmelCase    (			self							: Tuple    )   ->List[Any]:



														"""simple docstring"""



														self.one_complete_example("""complete_nlp_example.py"""						,    UpperCAmelCase_    )
														self.one_complete_example("""complete_nlp_example.py"""						,    UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: Tuple    )   ->Dict:



														"""simple docstring"""



														snake_case_          =						os.path.abspath(os.path.join("""examples"""						,    """cv_example.py"""    )    )
														snake_case_          =						[
														    """ """ * 16 + """{\n\n""",
														    """ """ * 20 + """\"accuracy\": eval_metric[\"accuracy\"],\n\n""",
														    """ """ * 20 + """\"f1\": eval_metric[\"f1\"],\n\n""",
														    """ """ * 20 + """\"train_loss\": total_loss.item() / len(train_dataloader),\n\n""",
														    """ """ * 20 + """\"epoch\": epoch,\n\n""",
														    """ """ * 16 + """},\n\n""",
														    """ """ * 16 + """step=epoch,\n""",
														    """ """ * 12,
														    """ """ * 8 + """for step, batch in enumerate(active_dataloader):\n""",
														]
														self.one_complete_example("""complete_cv_example.py"""						,    UpperCAmelCase_						,    UpperCAmelCase_						,    UpperCAmelCase_    )
														self.one_complete_example("""complete_cv_example.py"""						,    UpperCAmelCase_						,    UpperCAmelCase_						,    UpperCAmelCase_    )





@mock.patch.dict(os.environ  ,						{"""TESTING_MOCKED_DATALOADERS""": """1"""})
class        __A       (snake_case__):





							'''simple docstring'''

							__lowercase:						str							 =      False



							@classmethod
							def 						lowerCAmelCase    (			cls							: Any    )   ->List[str]:



														"""simple docstring"""



														super().setUpClass()
														snake_case_          =						tempfile.mkdtemp()
														snake_case_          =						os.path.join(cls._tmpdir						,    """default_config.yml"""    )

														write_basic_config(save_location=cls.configPath    )
														snake_case_          =						["""accelerate""", """launch""", """--config_file""", cls.configPath]



							@classmethod
							def 						lowerCAmelCase    (			cls							: List[str]    )   ->int:



														"""simple docstring"""



														super().tearDownClass()
														shutil.rmtree(cls._tmpdir    )



							def 						lowerCAmelCase    (			self							: List[str]    )   ->Optional[Any]:



														"""simple docstring"""



														snake_case_          =						F"""
        examples/by_feature/checkpointing.py
        --checkpointing_steps epoch
        --output_dir {self.tmpdir}
        """.split()
														run_command(self._launch_args + testargs    )
														self.assertTrue(os.path.exists(os.path.join(self.tmpdir						,    """epoch_0"""    )    )    )



							def 						lowerCAmelCase    (			self							: Any    )   ->Optional[Any]:



														"""simple docstring"""



														snake_case_          =						F"""
        examples/by_feature/checkpointing.py
        --checkpointing_steps 1
        --output_dir {self.tmpdir}
        """.split()
														snake_case_          =						run_command(self._launch_args + testargs    )
														self.assertTrue(os.path.exists(os.path.join(self.tmpdir						,    """step_2"""    )    )    )



							def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->str:



														"""simple docstring"""



														snake_case_          =						F"""
        examples/by_feature/checkpointing.py
        --resume_from_checkpoint {os.path.join(self.tmpdir						,    "epoch_0"    )}
        """.split()
														snake_case_          =						run_command(self._launch_args + testargs						,    return_stdout=UpperCAmelCase_    )
														self.assertNotIn("""epoch 0:"""						,    UpperCAmelCase_    )
														self.assertIn("""epoch 1:"""						,    UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->Tuple:



														"""simple docstring"""



														snake_case_          =						F"""
        examples/by_feature/checkpointing.py
        --resume_from_checkpoint {os.path.join(self.tmpdir						,    "step_2"    )}
        """.split()
														snake_case_          =						run_command(self._launch_args + testargs						,    return_stdout=UpperCAmelCase_    )
														if torch.cuda.is_available():
																					snake_case_          =						torch.cuda.device_count()
														else:
																					snake_case_          =						1
														if num_processes > 1:
																					self.assertNotIn("""epoch 0:"""						,    UpperCAmelCase_    )
																					self.assertIn("""epoch 1:"""						,    UpperCAmelCase_    )
														else:
																					self.assertIn("""epoch 0:"""						,    UpperCAmelCase_    )
																					self.assertIn("""epoch 1:"""						,    UpperCAmelCase_    )



							@slow
							def 						lowerCAmelCase    (			self							: Dict    )   ->Dict:



														"""simple docstring"""



														snake_case_          =						"""
        examples/by_feature/cross_validation.py
        --num_folds 2
        """.split()
														with mock.patch.dict(os.environ						,    {"""TESTING_MOCKED_DATALOADERS""": """0"""}    ):
																					snake_case_          =						run_command(self._launch_args + testargs						,    return_stdout=UpperCAmelCase_    )
																					snake_case_          =						re.findall("""({.+})"""						,    UpperCAmelCase_    )
																					snake_case_          =						[r for r in results if """accuracy""" in r][-1]
																					snake_case_          =						ast.literal_eval(UpperCAmelCase_    )
																					self.assertGreaterEqual(results["""accuracy"""]						,    0.75    )



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->int:



														"""simple docstring"""



														snake_case_          =						["""examples/by_feature/multi_process_metrics.py"""]
														run_command(self._launch_args + testargs    )



							@require_trackers
							@mock.patch.dict(os.environ						,    {"""WANDB_MODE""": """offline"""}    )
							def 						lowerCAmelCase    (			self							: Dict    )   ->Optional[Any]:



														"""simple docstring"""



														with tempfile.TemporaryDirectory() as tmpdir:
																					snake_case_          =						F"""
            examples/by_feature/tracking.py
            --with_tracking
            --project_dir {tmpdir}
            """.split()
																					run_command(self._launch_args + testargs    )
																					self.assertTrue(os.path.exists(os.path.join(UpperCAmelCase_						,    """tracking"""    )    )    )



							def 						lowerCAmelCase    (			self							: List[str]    )   ->Union[str, Any]:



														"""simple docstring"""



														snake_case_          =						["""examples/by_feature/gradient_accumulation.py"""]
														run_command(self._launch_args + testargs    )



							def 						lowerCAmelCase    (			self							: str    )   ->Dict:



														"""simple docstring"""



														snake_case_          =						["""examples/by_feature/local_sgd.py"""]
														run_command(self._launch_args + testargs    )



