

import pytest
import requests

from datasets.utils.file_utils import http_head

from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline

@pytest.mark.integration
def      snake_case__      (   ):



     '''simple docstring'''





     with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT      ):
          with pytest.raises(lowercase__      ):
               requests.request('GET'     ,					'https://huggingface.co'      )
          with pytest.raises(requests.exceptions.ConnectTimeout      ):
               requests.request('GET'     ,					'https://huggingface.co'     ,					timeout=1.0      )

@pytest.mark.integration
def      snake_case__      (   ):



     '''simple docstring'''





     with offline(OfflineSimulationMode.CONNECTION_FAILS      ):
          with pytest.raises(requests.exceptions.ConnectionError      ):
               requests.request('GET'     ,					'https://huggingface.co'      )

def      snake_case__      (   ):



     '''simple docstring'''





     with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1      ):
          with pytest.raises(lowercase__      ):
               http_head('https://huggingface.co'      )




import argparse
import os

import numpy as np
import tensorflow as tf
import torch

from transformers import BertModel

def      snake_case__      (   SCREAMING_SNAKE_CASE_		:   BertModel     ,					SCREAMING_SNAKE_CASE_		:   str     ,					SCREAMING_SNAKE_CASE_		:   str      ):



     '''simple docstring'''





     lowercase__   :       Tuple				=	('dense.weight', 'attention.self.query', 'attention.self.key', 'attention.self.value')

     lowercase__   :       Dict				=	(
         ('layer.', 'layer_'),
         ('word_embeddings.weight', 'word_embeddings'),
         ('position_embeddings.weight', 'position_embeddings'),
         ('token_type_embeddings.weight', 'token_type_embeddings'),
         ('.', '/'),
         ('LayerNorm/weight', 'LayerNorm/gamma'),
         ('LayerNorm/bias', 'LayerNorm/beta'),
         ('weight', 'kernel'),
     )

     if not os.path.isdir(SCREAMING_SNAKE_CASE_      ):
          os.makedirs(SCREAMING_SNAKE_CASE_      )

     lowercase__   :       str				=	model.state_dict()

     def to_tf_var_name(SCREAMING_SNAKE_CASE_		:   str      ):
          for patt, repl in iter(SCREAMING_SNAKE_CASE_      ):
               lowercase__   :       Optional[int]				=	name.replace(SCREAMING_SNAKE_CASE_     ,					SCREAMING_SNAKE_CASE_      )
          return f"""bert/{name}"""

     def create_tf_var(SCREAMING_SNAKE_CASE_		:   np.ndarray     ,					SCREAMING_SNAKE_CASE_		:   str     ,					SCREAMING_SNAKE_CASE_		:   tf.Session      ):
          lowercase__   :       Optional[Any]				=	tf.dtypes.as_dtype(tensor.dtype      )
          lowercase__   :       List[str]				=	tf.get_variable(dtype=SCREAMING_SNAKE_CASE_     ,					shape=tensor.shape     ,					name=SCREAMING_SNAKE_CASE_     ,					initializer=tf.zeros_initializer()      )
          session.run(tf.variables_initializer([tf_var]      )      )
          session.run(SCREAMING_SNAKE_CASE_      )
          return tf_var

     tf.reset_default_graph()
     with tf.Session() as session:
          for var_name in state_dict:
               lowercase__   :       Tuple				=	to_tf_var_name(SCREAMING_SNAKE_CASE_      )
               lowercase__   :       str				=	state_dict[var_name].numpy()
               if any(x in var_name for x in tensors_to_transpose      ):
                    lowercase__   :       str				=	torch_tensor.T
               lowercase__   :       Any				=	create_tf_var(tensor=SCREAMING_SNAKE_CASE_     ,					name=SCREAMING_SNAKE_CASE_     ,					session=SCREAMING_SNAKE_CASE_      )
               tf.keras.backend.set_value(SCREAMING_SNAKE_CASE_     ,					SCREAMING_SNAKE_CASE_      )
               lowercase__   :       Optional[int]				=	session.run(SCREAMING_SNAKE_CASE_      )
               print(f"""Successfully created {tf_name}: {np.allclose(SCREAMING_SNAKE_CASE_     ,					SCREAMING_SNAKE_CASE_      )}"""      )

          lowercase__   :       Tuple				=	tf.train.Saver(tf.trainable_variables()      )
          saver.save(SCREAMING_SNAKE_CASE_     ,					os.path.join(SCREAMING_SNAKE_CASE_     ,					model_name.replace('-'     ,					'_'      ) + '.ckpt'      )      )

def      snake_case__      (   SCREAMING_SNAKE_CASE_		:   Optional[Any]=None      ):



     '''simple docstring'''





     lowercase__   :       List[str]				=	argparse.ArgumentParser()
     parser.add_argument('--model_name'     ,					type=SCREAMING_SNAKE_CASE_     ,					required=SCREAMING_SNAKE_CASE_     ,					help='model name e.g. bert-base-uncased'      )
     parser.add_argument(
         '--cache_dir'     ,					type=SCREAMING_SNAKE_CASE_     ,					default=SCREAMING_SNAKE_CASE_     ,					required=SCREAMING_SNAKE_CASE_     ,					help='Directory containing pytorch model'      )
     parser.add_argument('--pytorch_model_path'     ,					type=SCREAMING_SNAKE_CASE_     ,					required=SCREAMING_SNAKE_CASE_     ,					help='/path/to/<pytorch-model-name>.bin'      )
     parser.add_argument('--tf_cache_dir'     ,					type=SCREAMING_SNAKE_CASE_     ,					required=SCREAMING_SNAKE_CASE_     ,					help='Directory in which to save tensorflow model'      )
     lowercase__   :       List[str]				=	parser.parse_args(SCREAMING_SNAKE_CASE_      )

     lowercase__   :       int				=	BertModel.from_pretrained(
         pretrained_model_name_or_path=args.model_name     ,					state_dict=torch.load(args.pytorch_model_path      )     ,					cache_dir=args.cache_dir     ,					)

     convert_pytorch_checkpoint_to_tf(model=SCREAMING_SNAKE_CASE_     ,					ckpt_dir=args.tf_cache_dir     ,					model_name=args.model_name      )


if __name__ == "__main__":
       main()

