
# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile


def     __lowerCAmelCase			(			a__						,    a__						,    a__						,    a__  )       ->  str:
				__a										=    multiprocessing.Manager()
				__a										=    manager.list()

				__a										=    multiprocessing.Process(target=a__						,    args=(check_program, result, timeout)  )
				p.start()
				p.join(timeout=timeout + 1  )
				if p.is_alive():
								p.kill()

				if not result:
								result.append('''timed out'''  )

				return {
				    "task_id": task_id,
				    "passed": result[0] == "passed",
				    "result": result[0],
				    "completion_id": completion_id,
				}


def     __lowerCAmelCase			(			a__						,    a__						,    a__  )       ->  List[Any]:
				with create_tempdir():
								# These system calls are needed when cleaning up tempdir.
								import os
								import shutil

								__a										=    shutil.rmtree
								__a										=    os.rmdir
								__a										=    os.chdir

								# Disable functionalities that can make destructive changes to the test.
								reliability_guard()

								# Run program.
								try:
												__a										=    {}
												with swallow_io():
																with time_limit(a__  ):
																				exec(a__						,    a__  )
												result.append('''passed'''  )
								except TimeoutException:
												result.append('''timed out'''  )
								except BaseException as e:
												result.append(F"""failed: {e}"""  )

								# Needed for cleaning up.
								__a										=    rmtree
								__a										=    rmdir
								__a										=    chdir


@contextlib.contextmanager
def     __lowerCAmelCase			(			a__  )       ->  str:
				def signal_handler(a__						,    a__  ):
								raise TimeoutException('''Timed out!'''  )

				signal.setitimer(signal.ITIMER_REAL						,    a__  )
				signal.signal(signal.SIGALRM						,    a__  )
				try:
								yield
				finally:
								signal.setitimer(signal.ITIMER_REAL						,    0  )


@contextlib.contextmanager
def     __lowerCAmelCase			(			)       ->  Tuple:
				__a										=    WriteOnlyStringIO()
				with contextlib.redirect_stdout(a__  ):
								with contextlib.redirect_stderr(a__  ):
												with redirect_stdin(a__  ):
																yield


@contextlib.contextmanager
def     __lowerCAmelCase			(			)       ->  Tuple:
				with tempfile.TemporaryDirectory() as dirname:
								with chdir(a__  ):
												yield dirname







class 			__A( a			):
				pass







class 			__A( io.StringIO			):




				def 				SCREAMING_SNAKE_CASE_		(     self		,     *_snake_case		,     **_snake_case				)    ->      int:


								'''simple docstring'''




								raise OSError




				def 				SCREAMING_SNAKE_CASE_		(     self		,     *_snake_case		,     **_snake_case				)    ->      List[Any]:


								'''simple docstring'''




								raise OSError




				def 				SCREAMING_SNAKE_CASE_		(     self		,     *_snake_case		,     **_snake_case				)    ->      List[Any]:


								'''simple docstring'''




								raise OSError




				def 				SCREAMING_SNAKE_CASE_		(     self		,     *_snake_case		,     **_snake_case				)    ->      Optional[int]:


								'''simple docstring'''




								return False







class 			__A( contextlib._RedirectStream			):  # type: ignore
				snake_case_						   =    '''stdin'''



@contextlib.contextmanager
def     __lowerCAmelCase			(			a__  )       ->  List[Any]:
				if root == ".":
								yield
								return
				__a										=    os.getcwd()
				os.chdir(a__  )
				try:
								yield
				except BaseException as exc:
								raise exc
				finally:
								os.chdir(a__  )






def     __lowerCAmelCase			(			a__=None  )       ->  Union[str, Any]:

				if maximum_memory_bytes is not None:
								import resource

								resource.setrlimit(resource.RLIMIT_AS						,    (maximum_memory_bytes, maximum_memory_bytes)  )
								resource.setrlimit(resource.RLIMIT_DATA						,    (maximum_memory_bytes, maximum_memory_bytes)  )
								if not platform.uname().system == "Darwin":
												resource.setrlimit(resource.RLIMIT_STACK						,    (maximum_memory_bytes, maximum_memory_bytes)  )

				faulthandler.disable()

				import builtins

				__a										=    None
				__a										=    None

				import os

				__a										=    '''1'''

				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None

				import shutil

				__a										=    None
				__a										=    None
				__a										=    None

				import subprocess

				__a										=    None  # type: ignore

				__a										=    None

				import sys

				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None
				__a										=    None

import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
					import os

					from flax.core.frozen_dict import unfreeze
					from flax.traverse_util import flatten_dict

					from transformers import FlaxBertModel

					A     :	int    = '0.12'  # assumed parallelism: 8







@require_flax
@is_staging_test
class 			__A( unittest.TestCase			):




				@classmethod
				def 				SCREAMING_SNAKE_CASE_		(     cls				)    ->      Union[str, Any]:


								'''simple docstring'''




								__a										=    TOKEN
								HfFolder.save_token(_snake_case				)




				@classmethod
				def 				SCREAMING_SNAKE_CASE_		(     cls				)    ->      Union[str, Any]:


								'''simple docstring'''




								try:
												delete_repo(token=cls._token		,     repo_id='''test-model-flax'''				)
								except HTTPError:
												pass

								try:
												delete_repo(token=cls._token		,     repo_id='''valid_org/test-model-flax-org'''				)
								except HTTPError:
												pass




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


								'''simple docstring'''




								__a										=    BertConfig(
								    vocab_size=99		,     hidden_size=32		,     num_hidden_layers=5		,     num_attention_heads=4		,     intermediate_size=37				)
								__a										=    FlaxBertModel(_snake_case				)
								model.push_to_hub('''test-model-flax'''		,     use_auth_token=self._token				)

								__a										=    FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""				)

								__a										=    flatten_dict(unfreeze(model.params				)				)
								__a										=    flatten_dict(unfreeze(new_model.params				)				)

								for key in base_params.keys():
												__a										=    (base_params[key] - new_params[key]).sum().item()
												self.assertLessEqual(_snake_case		,     1E-3		,     msg=F"""{key} not identical"""				)

								# Reset repo
								delete_repo(token=self._token		,     repo_id='''test-model-flax'''				)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
												model.save_pretrained(_snake_case		,     repo_id='''test-model-flax'''		,     push_to_hub=_snake_case		,     use_auth_token=self._token				)

								__a										=    FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""				)

								__a										=    flatten_dict(unfreeze(model.params				)				)
								__a										=    flatten_dict(unfreeze(new_model.params				)				)

								for key in base_params.keys():
												__a										=    (base_params[key] - new_params[key]).sum().item()
												self.assertLessEqual(_snake_case		,     1E-3		,     msg=F"""{key} not identical"""				)




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


								'''simple docstring'''




								__a										=    BertConfig(
								    vocab_size=99		,     hidden_size=32		,     num_hidden_layers=5		,     num_attention_heads=4		,     intermediate_size=37				)
								__a										=    FlaxBertModel(_snake_case				)
								model.push_to_hub('''valid_org/test-model-flax-org'''		,     use_auth_token=self._token				)

								__a										=    FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''				)

								__a										=    flatten_dict(unfreeze(model.params				)				)
								__a										=    flatten_dict(unfreeze(new_model.params				)				)

								for key in base_params.keys():
												__a										=    (base_params[key] - new_params[key]).sum().item()
												self.assertLessEqual(_snake_case		,     1E-3		,     msg=F"""{key} not identical"""				)

								# Reset repo
								delete_repo(token=self._token		,     repo_id='''valid_org/test-model-flax-org'''				)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
												model.save_pretrained(
												    _snake_case		,     repo_id='''valid_org/test-model-flax-org'''		,     push_to_hub=_snake_case		,     use_auth_token=self._token				)

								__a										=    FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''				)

								__a										=    flatten_dict(unfreeze(model.params				)				)
								__a										=    flatten_dict(unfreeze(new_model.params				)				)

								for key in base_params.keys():
												__a										=    (base_params[key] - new_params[key]).sum().item()
												self.assertLessEqual(_snake_case		,     1E-3		,     msg=F"""{key} not identical"""				)



def     __lowerCAmelCase			(			a__						,    a__  )       ->  str:
				__a										=    True
				__a										=    flatten_dict(modela.params  )
				__a										=    flatten_dict(modela.params  )
				for key in flat_params_a.keys():
								if np.sum(np.abs(flat_params_a[key] - flat_params_a[key]  )  ) > 1e-4:
												__a										=    False

				return models_are_equal







@require_flax
class 			__A( unittest.TestCase			):




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


								'''simple docstring'''




								__a										=    BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''				)
								__a										=    FlaxBertModel(_snake_case				)

								__a										=    '''bert'''
								with tempfile.TemporaryDirectory() as tmp_dir:
												model.save_pretrained(os.path.join(_snake_case		,     _snake_case				)				)

												with self.assertRaises(_snake_case				):
																__a										=    FlaxBertModel.from_pretrained(_snake_case				)

												__a										=    FlaxBertModel.from_pretrained(_snake_case		,     subfolder=_snake_case				)

								self.assertTrue(check_models_equal(_snake_case		,     _snake_case				)				)




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


								'''simple docstring'''




								__a										=    BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''				)
								__a										=    FlaxBertModel(_snake_case				)

								__a										=    '''bert'''
								with tempfile.TemporaryDirectory() as tmp_dir:
												model.save_pretrained(os.path.join(_snake_case		,     _snake_case				)		,     max_shard_size='''10KB'''				)

												with self.assertRaises(_snake_case				):
																__a										=    FlaxBertModel.from_pretrained(_snake_case				)

												__a										=    FlaxBertModel.from_pretrained(_snake_case		,     subfolder=_snake_case				)

								self.assertTrue(check_models_equal(_snake_case		,     _snake_case				)				)




				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      int:


								'''simple docstring'''




								__a										=    '''bert'''
								__a										=    '''hf-internal-testing/tiny-random-bert-subfolder'''

								with self.assertRaises(_snake_case				):
												__a										=    FlaxBertModel.from_pretrained(_snake_case				)

								__a										=    FlaxBertModel.from_pretrained(_snake_case		,     subfolder=_snake_case				)

								self.assertIsNotNone(_snake_case				)




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


								'''simple docstring'''




								__a										=    '''bert'''
								__a										=    '''hf-internal-testing/tiny-random-bert-sharded-subfolder'''
								with self.assertRaises(_snake_case				):
												__a										=    FlaxBertModel.from_pretrained(_snake_case				)

								__a										=    FlaxBertModel.from_pretrained(_snake_case		,     subfolder=_snake_case				)

								self.assertIsNotNone(_snake_case				)