'''simple docstring'''




import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch




class    a__				(       UpperCAmelCase__			):






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  '''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        '''

         __lowerCamelCase          =  '''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
        '''

         __lowerCamelCase          =  '''
import socket
def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")
socket.socket = offline_socket
        '''

         # Force fetching the files so that we can use the cache
         __lowerCamelCase          =  '''hf-internal-testing/tiny-random-bert'''
         BertConfig.from_pretrained(a   )
         BertModel.from_pretrained(a   )
         BertTokenizer.from_pretrained(a   )
         pipeline(task='''fill-mask'''  ,    model=a   )

         # baseline - just load from_pretrained with normal network
         __lowerCamelCase          =  [sys.executable, '''-c''', '''\n'''.join([load, run, mock]   )]

         # should succeed
         __lowerCamelCase          =  self.get_env()
         # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
         __lowerCamelCase          =  '''1'''
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    0  ,    result.stderr   )
         self.assertIn('''success'''  ,    result.stdout.decode()   )






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  '''
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
        '''

         __lowerCamelCase          =  '''
mname = "hf-internal-testing/tiny-random-bert"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
BertTokenizer.from_pretrained(mname)
pipe = pipeline(task="fill-mask", model=mname)
print("success")
        '''

         __lowerCamelCase          =  '''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")
socket.socket = offline_socket
        '''

         # Force fetching the files so that we can use the cache
         __lowerCamelCase          =  '''hf-internal-testing/tiny-random-bert'''
         BertConfig.from_pretrained(a   )
         BertModel.from_pretrained(a   )
         BertTokenizer.from_pretrained(a   )
         pipeline(task='''fill-mask'''  ,    model=a   )

         # baseline - just load from_pretrained with normal network
         __lowerCamelCase          =  [sys.executable, '''-c''', '''\n'''.join([load, run, mock]   )]

         # should succeed
         __lowerCamelCase          =  self.get_env()
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    0  ,    result.stderr   )
         self.assertIn('''success'''  ,    result.stdout.decode()   )






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  '''
from transformers import BertConfig, BertModel, BertTokenizer
        '''

         __lowerCamelCase          =  '''
mname = "hf-internal-testing/tiny-random-bert-sharded"
BertConfig.from_pretrained(mname)
BertModel.from_pretrained(mname)
print("success")
        '''

         __lowerCamelCase          =  '''
import socket
def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")
socket.socket = offline_socket
        '''

         # baseline - just load from_pretrained with normal network
         __lowerCamelCase          =  [sys.executable, '''-c''', '''\n'''.join([load, run]   )]

         # should succeed
         __lowerCamelCase          =  self.get_env()
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    0  ,    result.stderr   )
         self.assertIn('''success'''  ,    result.stdout.decode()   )

         # next emulate no network
         __lowerCamelCase          =  [sys.executable, '''-c''', '''\n'''.join([load, mock, run]   )]

         # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
         # env["TRANSFORMERS_OFFLINE"] = "0"
         # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
         # self.assertEqual(result.returncode, 1, result.stderr)

         # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
         __lowerCamelCase          =  '''1'''
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    0  ,    result.stderr   )
         self.assertIn('''success'''  ,    result.stdout.decode()   )






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         __lowerCamelCase          =  '''
from transformers import pipeline
        '''
         __lowerCamelCase          =  '''
mname = "hf-internal-testing/tiny-random-bert"
pipe = pipeline(model=mname)
        '''

         __lowerCamelCase          =  '''
import socket
def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")
socket.socket = offline_socket
        '''
         __lowerCamelCase          =  self.get_env()
         __lowerCamelCase          =  '''1'''
         __lowerCamelCase          =  [sys.executable, '''-c''', '''\n'''.join([load, mock, run]   )]
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    1  ,    result.stderr   )
         self.assertIn(
             '''You cannot infer task automatically within `pipeline` when using offline mode'''  ,    result.stderr.decode().replace('''\n'''  ,    ''''''   )  ,    )






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  '''
from transformers import AutoModel
        '''
         __lowerCamelCase          =  '''
mname = "hf-internal-testing/test_dynamic_model"
AutoModel.from_pretrained(mname, trust_remote_code=True)
print("success")
        '''

         # baseline - just load from_pretrained with normal network
         __lowerCamelCase          =  [sys.executable, '''-c''', '''\n'''.join([load, run]   )]

         # should succeed
         __lowerCamelCase          =  self.get_env()
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    0  ,    result.stderr   )
         self.assertIn('''success'''  ,    result.stdout.decode()   )

         # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
         __lowerCamelCase          =  '''1'''
         __lowerCamelCase          =  subprocess.run(a  ,    env=a  ,    check=a  ,    capture_output=a   )
         self.assertEqual(result.returncode  ,    0  ,    result.stderr   )
         self.assertIn('''success'''  ,    result.stdout.decode()   )

'''simple docstring'''




import time
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
  import torch

  from transformers.generation import (
      MaxLengthCriteria,
      MaxNewTokensCriteria,
      MaxTimeCriteria,
      StoppingCriteriaList,
      validate_stopping_criteria,
  )




@require_torch
class    a__				(       unittest.TestCase			):






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]  ,    a		:		int   ):





         """simple docstring"""



         __lowerCamelCase          =  3
         __lowerCamelCase          =  2_50

         __lowerCamelCase          =  ids_tensor((batch_size, length)  ,    a   )
         __lowerCamelCase          =  torch.ones((batch_size, length)  ,    device=a  ,    dtype=torch.float   ) / length
         return input_ids, scores






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )

         __lowerCamelCase          =  StoppingCriteriaList(
             [
                 MaxLengthCriteria(max_length=10   ),
                 MaxTimeCriteria(max_time=0.1   ),
             ]   )

         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(9   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(10   )
         self.assertTrue(criteria(a  ,    a   )   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  MaxLengthCriteria(max_length=10   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(9   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(10   )
         self.assertTrue(criteria(a  ,    a   )   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  MaxNewTokensCriteria(start_length=5  ,    max_new_tokens=5   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(9   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(10   )
         self.assertTrue(criteria(a  ,    a   )   )

         __lowerCamelCase          =  StoppingCriteriaList([criteria]   )
         self.assertEqual(criteria_list.max_length  ,    10   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         __lowerCamelCase     ,  __lowerCamelCase          =  self._get_tensors(5   )

         __lowerCamelCase          =  MaxTimeCriteria(max_time=0.1   )
         self.assertFalse(criteria(a  ,    a   )   )

         __lowerCamelCase          =  MaxTimeCriteria(max_time=0.1  ,    initial_timestamp=time.time() - 0.2   )
         self.assertTrue(criteria(a  ,    a   )   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10   )]   )  ,    10   )

         with self.assertWarns(a   ):
             validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10   )]   )  ,    11   )

         __lowerCamelCase          =  validate_stopping_criteria(StoppingCriteriaList()  ,    11   )

         self.assertEqual(len(a   )  ,    1   )
