






'''simple docstring'''
import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil






class    __SCREAMING_SNAKE_CASE					(	__SCREAMING_SNAKE_CASE ):




 def    __magic_name__		(					self		:							List[str]					)		->  Union[str, Any]:
       SCREAMING_SNAKE_CASE__   : Tuple													=pa.array(TypedSequence([1, 2, 3]					)					)
       self.assertEqual(arr.type    ,					pa.intaa()					)




 def    __magic_name__		(					self		:							List[str]					)		->  Tuple:

       with self.assertRaises(_SCREAMING_SNAKE_CASE					):
             SCREAMING_SNAKE_CASE__   : int													=pa.array(TypedSequence([1, 2, 3]					)    ,					type=pa.intaa()					)




 def    __magic_name__		(					self		:							List[str]					)		->  str:

       with self.assertRaises(_SCREAMING_SNAKE_CASE					):
             SCREAMING_SNAKE_CASE__   : Optional[Any]													=pa.array(TypedSequence([1, 2, 3]    ,					try_type=Value('''bool'''					)    ,					type=Value('''int64'''					)					)					)




 def    __magic_name__		(					self		:							Optional[Any]					)		->  Dict:
       SCREAMING_SNAKE_CASE__   : str													=pa.array(TypedSequence([1, 2, 3]    ,					type=Value('''int32'''					)					)					)
       self.assertEqual(arr.type    ,					pa.intaa()					)




 def    __magic_name__		(					self		:							Optional[Any]					)		->  Tuple:

       with self.assertRaises((TypeError, pa.lib.ArrowInvalid)					):
             SCREAMING_SNAKE_CASE__   : Optional[Any]													=pa.array(TypedSequence(['''foo''', '''bar''']    ,					type=Value('''int64'''					)					)					)




 def    __magic_name__		(					self		:							Optional[int]					)		->  Dict:
       SCREAMING_SNAKE_CASE__   : Tuple													=pa.array(TypedSequence([1, 2, 3]    ,					try_type=Value('''int32'''					)					)					)
       self.assertEqual(arr.type    ,					pa.intaa()					)




 def    __magic_name__		(					self		:							List[Any]					)		->  str:
       SCREAMING_SNAKE_CASE__   : Union[str, Any]													=pa.array(TypedSequence(['''foo''', '''bar''']    ,					try_type=Value('''int64'''					)					)					)
       self.assertEqual(arr.type    ,					pa.string()					)




 def    __magic_name__		(					self		:							Union[str, Any]					)		->  Any:
       SCREAMING_SNAKE_CASE__   : Tuple													=pa.array(TypedSequence([[[1, 2, 3]]]    ,					type=ArrayaD((1, 3)    ,					'''int64'''					)					)					)
       self.assertEqual(arr.type    ,					ArrayaDExtensionType((1, 3)    ,					'''int64'''					)					)




 def    __magic_name__		(					self		:							Optional[int]					)		->  Any:

       with self.assertRaises((TypeError, pa.lib.ArrowInvalid)					):
             SCREAMING_SNAKE_CASE__   : int													=pa.array(TypedSequence(['''foo''', '''bar''']    ,					type=ArrayaD((1, 3)    ,					'''int64'''					)					)					)




 def    __magic_name__		(					self		:							List[str]					)		->  str:
       SCREAMING_SNAKE_CASE__   : int													=pa.array(TypedSequence([[[1, 2, 3]]]    ,					try_type=ArrayaD((1, 3)    ,					'''int64'''					)					)					)
       self.assertEqual(arr.type    ,					ArrayaDExtensionType((1, 3)    ,					'''int64'''					)					)




 def    __magic_name__		(					self		:							Tuple					)		->  List[Any]:
       SCREAMING_SNAKE_CASE__   : Union[str, Any]													=pa.array(TypedSequence(['''foo''', '''bar''']    ,					try_type=ArrayaD((1, 3)    ,					'''int64'''					)					)					)
       self.assertEqual(arr.type    ,					pa.string()					)




 @require_pil
 def    __magic_name__		(					self		:							Tuple					)		->  Tuple:
       import PIL.Image

       SCREAMING_SNAKE_CASE__   : Dict													=PIL.Image.fromarray(np.arange(10    ,					dtype=np.uinta					).reshape(2    ,					5					)					)
       with patch(
           '''datasets.arrow_writer.cast_to_python_objects'''    ,					side_effect=_SCREAMING_SNAKE_CASE					) as mock_cast_to_python_objects:
             SCREAMING_SNAKE_CASE__   : Union[str, Any]													=pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image]    ,					type=Image()					)					)
             SCREAMING_SNAKE_CASE__   : Optional[int]													=mock_cast_to_python_objects.call_args_list[-1]
             self.assertIn('''optimize_list_casting'''    ,					_SCREAMING_SNAKE_CASE					)
             self.assertFalse(kwargs['''optimize_list_casting''']					)





def        _a(     UpperCamelCase__ :  Optional[Any],		UpperCamelCase__ :  List[str]							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Dict													=pa.BufferReader(__snake_case							) if isinstance(__snake_case,		pa.Buffer							) else pa.memory_map(__snake_case							)
      SCREAMING_SNAKE_CASE__   : Union[str, Any]													=pa.ipc.open_stream(__snake_case							)
      SCREAMING_SNAKE_CASE__   : pa.Table													=f.read_all()
      assert len(pa_table.to_batches()							) == expected_num_chunks
      assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
      del pa_table





@pytest.mark.parametrize('''writer_batch_size''',		[None, 1, 1_0]							)
@pytest.mark.parametrize(
    '''fields''',		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]							)
def        _a(     UpperCamelCase__ :  Union[str, Any],		UpperCamelCase__ :  Dict							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : List[str]													=pa.BufferOutputStream()
      SCREAMING_SNAKE_CASE__   : Optional[int]													=pa.schema(__snake_case							) if fields else None
      with ArrowWriter(stream=__snake_case,		schema=__snake_case,		writer_batch_size=__snake_case							) as writer:
            writer.write({'''col_1''': '''foo''', '''col_2''': 1}							)
            writer.write({'''col_1''': '''bar''', '''col_2''': 2}							)
            SCREAMING_SNAKE_CASE__   : List[Any]													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      if not fields:
            SCREAMING_SNAKE_CASE__   : List[Any]													={"col_1": pa.string(), "col_2": pa.intaa()}
      assert writer._schema == pa.schema(__snake_case,		metadata=writer._schema.metadata							)
      _check_output(output.getvalue(),		expected_num_chunks=num_examples if writer_batch_size == 1 else 1							)





def        _a(     ):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Any													=pa.BufferOutputStream()
      SCREAMING_SNAKE_CASE__   : str													=Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']							)}							)
      with ArrowWriter(stream=__snake_case,		features=__snake_case							) as writer:
            writer.write({'''labels''': 0}							)
            writer.write({'''labels''': 1}							)
            SCREAMING_SNAKE_CASE__   : Tuple													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      assert writer._schema == features.arrow_schema
      assert writer._schema.metadata == features.arrow_schema.metadata
      SCREAMING_SNAKE_CASE__   : Tuple													=pa.BufferReader(output.getvalue()							)
      SCREAMING_SNAKE_CASE__   : List[Any]													=pa.ipc.open_stream(__snake_case							)
      SCREAMING_SNAKE_CASE__   : pa.Table													=f.read_all()
      SCREAMING_SNAKE_CASE__   : Any													=pa_table.schema
      assert pa_table.num_rows == 2
      assert schema == features.arrow_schema
      assert schema.metadata == features.arrow_schema.metadata
      assert features == Features.from_arrow_schema(__snake_case							)





@pytest.mark.parametrize('''writer_batch_size''',		[None, 1, 1_0]							)
def        _a(     UpperCamelCase__ :  Optional[int]							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Union[str, Any]													=pa.BufferOutputStream()
      with ArrowWriter(
          stream=__snake_case,		writer_batch_size=__snake_case,		hash_salt='''split_name''',		check_duplicates=__snake_case,		) as writer:
            with pytest.raises(__snake_case							):
                  writer.write({'''col_1''': '''foo''', '''col_2''': 1},		key=[1, 2]							)
                  SCREAMING_SNAKE_CASE__   : Optional[Any]													=writer.finalize()





@pytest.mark.parametrize('''writer_batch_size''',		[None, 2, 1_0]							)
def        _a(     UpperCamelCase__ :  str							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Tuple													=pa.BufferOutputStream()
      with ArrowWriter(
          stream=__snake_case,		writer_batch_size=__snake_case,		hash_salt='''split_name''',		check_duplicates=__snake_case,		) as writer:
            with pytest.raises(__snake_case							):
                  writer.write({'''col_1''': '''foo''', '''col_2''': 1},		key=1_0							)
                  writer.write({'''col_1''': '''bar''', '''col_2''': 2},		key=1_0							)
                  SCREAMING_SNAKE_CASE__   : Optional[Any]													=writer.finalize()





@pytest.mark.parametrize('''writer_batch_size''',		[None, 2, 1_0]							)
def        _a(     UpperCamelCase__ :  Union[str, Any]							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : List[str]													=pa.BufferOutputStream()
      with ArrowWriter(
          stream=__snake_case,		writer_batch_size=__snake_case,		hash_salt='''split_name''',		check_duplicates=__snake_case,		) as writer:
            writer.write({'''col_1''': '''foo''', '''col_2''': 1},		key=1							)
            writer.write({'''col_1''': '''bar''', '''col_2''': 2},		key=2							)
            SCREAMING_SNAKE_CASE__   : Union[str, Any]													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      _check_output(output.getvalue(),		expected_num_chunks=num_examples if writer_batch_size == 1 else 1							)





@pytest.mark.parametrize('''writer_batch_size''',		[None, 1, 1_0]							)
@pytest.mark.parametrize(
    '''fields''',		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]							)
def        _a(     UpperCamelCase__ :  str,		UpperCamelCase__ :  Tuple							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Dict													=pa.BufferOutputStream()
      SCREAMING_SNAKE_CASE__   : Union[str, Any]													=pa.schema(__snake_case							) if fields else None
      with ArrowWriter(stream=__snake_case,		schema=__snake_case,		writer_batch_size=__snake_case							) as writer:
            writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}							)
            writer.write_batch({'''col_1''': [], '''col_2''': []}							)
            SCREAMING_SNAKE_CASE__   : str													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      if not fields:
            SCREAMING_SNAKE_CASE__   : List[str]													={"col_1": pa.string(), "col_2": pa.intaa()}
      assert writer._schema == pa.schema(__snake_case,		metadata=writer._schema.metadata							)
      _check_output(output.getvalue(),		expected_num_chunks=num_examples if writer_batch_size == 1 else 1							)





@pytest.mark.parametrize('''writer_batch_size''',		[None, 1, 1_0]							)
@pytest.mark.parametrize(
    '''fields''',		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]							)
def        _a(     UpperCamelCase__ :  Any,		UpperCamelCase__ :  str							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : int													=pa.BufferOutputStream()
      SCREAMING_SNAKE_CASE__   : Tuple													=pa.schema(__snake_case							) if fields else None
      with ArrowWriter(stream=__snake_case,		schema=__snake_case,		writer_batch_size=__snake_case							) as writer:
            writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}							)							)
            SCREAMING_SNAKE_CASE__   : Dict													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      if not fields:
            SCREAMING_SNAKE_CASE__   : int													={"col_1": pa.string(), "col_2": pa.intaa()}
      assert writer._schema == pa.schema(__snake_case,		metadata=writer._schema.metadata							)
      _check_output(output.getvalue(),		expected_num_chunks=num_examples if writer_batch_size == 1 else 1							)





@pytest.mark.parametrize('''writer_batch_size''',		[None, 1, 1_0]							)
@pytest.mark.parametrize(
    '''fields''',		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]							)
def        _a(     UpperCamelCase__ :  Dict,		UpperCamelCase__ :  List[str]							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : str													=pa.BufferOutputStream()
      SCREAMING_SNAKE_CASE__   : Dict													=pa.schema(__snake_case							) if fields else None
      with ArrowWriter(stream=__snake_case,		schema=__snake_case,		writer_batch_size=__snake_case							) as writer:
            writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}							)							)
            writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}							)							)
            SCREAMING_SNAKE_CASE__   : Tuple													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      if not fields:
            SCREAMING_SNAKE_CASE__   : int													={"col_1": pa.string(), "col_2": pa.intaa()}
      assert writer._schema == pa.schema(__snake_case,		metadata=writer._schema.metadata							)
      _check_output(output.getvalue(),		expected_num_chunks=num_examples if writer_batch_size == 1 else 1							)





def        _a(     ):




      '''simple docstring'''






      with tempfile.TemporaryDirectory() as tmp_dir:
            SCREAMING_SNAKE_CASE__   : int													={"col_1": pa.string(), "col_2": pa.intaa()}
            SCREAMING_SNAKE_CASE__   : Tuple													=os.path.join(__snake_case,		'''test.arrow'''							)
            with ArrowWriter(path=__snake_case,		schema=pa.schema(__snake_case							)							) as writer:
                  writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}							)
                  SCREAMING_SNAKE_CASE__   : Any													=writer.finalize()
            assert num_examples == 2
            assert num_bytes > 0
            assert writer._schema == pa.schema(__snake_case,		metadata=writer._schema.metadata							)
            _check_output(__snake_case,		1							)





def        _a(     UpperCamelCase__ :  int							):




      '''simple docstring'''






      if pa.types.is_list(__snake_case							):
            return get_base_dtype(arr_type.value_type							)
      else:
            return arr_type





def        _a(     UpperCamelCase__ :  str,		UpperCamelCase__ :  List[str]							):




      '''simple docstring'''






      if isinstance(lst[0],		__snake_case							):
            change_first_primitive_element_in_list(lst[0],		__snake_case							)
      else:
            SCREAMING_SNAKE_CASE__   : Tuple													=value





@pytest.mark.parametrize('''optimized_int_type, expected_dtype''',		[(None, pa.intaa()), (Value('''int32'''							), pa.intaa())]							)
@pytest.mark.parametrize('''sequence''',		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]							)
def        _a(     UpperCamelCase__ :  Optional[Any],		UpperCamelCase__ :  Any,		UpperCamelCase__ :  Any							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : str													=pa.array(TypedSequence(__snake_case,		optimized_int_type=__snake_case							)							)
      assert get_base_dtype(arr.type							) == expected_dtype





@pytest.mark.parametrize(
    '''col, expected_dtype''',		[
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ],		)
@pytest.mark.parametrize('''sequence''',		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]							)
def        _a(     UpperCamelCase__ :  Union[str, Any],		UpperCamelCase__ :  Optional[Any],		UpperCamelCase__ :  List[Any]							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Dict													=pa.array(OptimizedTypedSequence(__snake_case,		col=__snake_case							)							)
      assert get_base_dtype(arr.type							) == expected_dtype

      # not in range
      if col != "other":
            # avoids errors due to in-place modifications
            SCREAMING_SNAKE_CASE__   : List[str]													=copy.deepcopy(__snake_case							)
            SCREAMING_SNAKE_CASE__   : str													=np.iinfo(expected_dtype.to_pandas_dtype()							).max + 1
            change_first_primitive_element_in_list(__snake_case,		__snake_case							)
            SCREAMING_SNAKE_CASE__   : Optional[int]													=pa.array(OptimizedTypedSequence(__snake_case,		col=__snake_case							)							)
            assert get_base_dtype(arr.type							) == pa.intaa()





@pytest.mark.parametrize('''raise_exception''',		[False, True]							)
def        _a(     UpperCamelCase__ :  Any,		UpperCamelCase__ :  Dict							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : str													=str(tmp_path / '''dataset-train.arrow'''							)
      try:
            with ArrowWriter(path=__snake_case							) as writer:
                  if raise_exception:
                        raise pa.lib.ArrowInvalid()
                  else:
                        writer.stream.close()
      except pa.lib.ArrowInvalid:
            pass
      finally:
            assert writer.stream.closed





def        _a(     UpperCamelCase__ :  Dict							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : List[Any]													="mock://dataset-train.arrow"
      with ArrowWriter(path=__snake_case,		storage_options=mockfs.storage_options							) as writer:
            assert isinstance(writer._fs,		type(__snake_case							)							)
            assert writer._fs.storage_options == mockfs.storage_options
            writer.write({'''col_1''': '''foo''', '''col_2''': 1}							)
            writer.write({'''col_1''': '''bar''', '''col_2''': 2}							)
            SCREAMING_SNAKE_CASE__   : int													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      assert mockfs.exists(__snake_case							)





def        _a(     ):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Tuple													=pa.BufferOutputStream()
      with ParquetWriter(stream=__snake_case							) as writer:
            writer.write({'''col_1''': '''foo''', '''col_2''': 1}							)
            writer.write({'''col_1''': '''bar''', '''col_2''': 2}							)
            SCREAMING_SNAKE_CASE__   : Union[str, Any]													=writer.finalize()
      assert num_examples == 2
      assert num_bytes > 0
      SCREAMING_SNAKE_CASE__   : str													=pa.BufferReader(output.getvalue()							)
      SCREAMING_SNAKE_CASE__   : pa.Table													=pq.read_table(__snake_case							)
      assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}





@require_pil
@pytest.mark.parametrize('''embed_local_files''',		[False, True]							)
def        _a(     UpperCamelCase__ :  Union[str, Any],		UpperCamelCase__ :  List[Any]							):




      '''simple docstring'''






      import PIL.Image

      SCREAMING_SNAKE_CASE__   : List[Any]													=str(tmp_path / '''test_image_rgb.jpg'''							)
      PIL.Image.fromarray(np.zeros((5, 5),		dtype=np.uinta							)							).save(__snake_case,		format='''png'''							)
      SCREAMING_SNAKE_CASE__   : Any													=pa.BufferOutputStream()
      with ParquetWriter(
          stream=__snake_case,		features=Features({'''image''': Image()}							),		embed_local_files=__snake_case							) as writer:
            writer.write({'''image''': image_path}							)
            writer.finalize()
      SCREAMING_SNAKE_CASE__   : int													=pa.BufferReader(output.getvalue()							)
      SCREAMING_SNAKE_CASE__   : pa.Table													=pq.read_table(__snake_case							)
      SCREAMING_SNAKE_CASE__   : List[Any]													=pa_table.to_pydict()
      if embed_local_files:
            assert isinstance(out['''image'''][0]['''path'''],		__snake_case							)
            with open(__snake_case,		'''rb'''							) as f:
                  assert out["image"][0]["bytes"] == f.read()
      else:
            assert out["image"][0]["path"] == image_path
            assert out["image"][0]["bytes"] is None







def        _a(     ):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : Dict													=pa.schema([pa.field('''col_1''',		pa.string(),		nullable=__snake_case							)]							)
      SCREAMING_SNAKE_CASE__   : List[str]													=pa.BufferOutputStream()
      with ArrowWriter(stream=__snake_case							) as writer:
            writer._build_writer(inferred_schema=__snake_case							)
            assert writer._schema == pa.schema([pa.field('''col_1''',		pa.string()							)]							)




"""simple docstring"""






import unittest

from transformers import SqueezeBertConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
	    SqueezeBertForMaskedLM,
	    SqueezeBertForMultipleChoice,
	    SqueezeBertForQuestionAnswering,
	    SqueezeBertForSequenceClassification,
	    SqueezeBertForTokenClassification,
	    SqueezeBertModel,
	)



class 			A__   (  __SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	def __init__(     self:		Tuple       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		List[str]=13       ,			_SCREAMING_SNAKE_CASE:		Tuple=7       ,			_SCREAMING_SNAKE_CASE:		int=True       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=True       ,			_SCREAMING_SNAKE_CASE:		str=False       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=True       ,			_SCREAMING_SNAKE_CASE:		int=99       ,			_SCREAMING_SNAKE_CASE:		int=32       ,			_SCREAMING_SNAKE_CASE:		List[str]=5       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=4       ,			_SCREAMING_SNAKE_CASE:		int=64       ,			_SCREAMING_SNAKE_CASE:		List[str]="gelu"       ,			_SCREAMING_SNAKE_CASE:		str=0.1       ,			_SCREAMING_SNAKE_CASE:		Any=0.1       ,			_SCREAMING_SNAKE_CASE:		Optional[int]=512       ,			_SCREAMING_SNAKE_CASE:		Tuple=16       ,			_SCREAMING_SNAKE_CASE:		Any=2       ,			_SCREAMING_SNAKE_CASE:		List[str]=0.02       ,			_SCREAMING_SNAKE_CASE:		Tuple=3       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=4       ,			_SCREAMING_SNAKE_CASE:		int=None       ,			_SCREAMING_SNAKE_CASE:		int=2       ,			_SCREAMING_SNAKE_CASE:		str=2       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=2       ,			_SCREAMING_SNAKE_CASE:		List[Any]=2       ,			_SCREAMING_SNAKE_CASE:		int=4       ,			_SCREAMING_SNAKE_CASE:		List[str]=1       ,			)				->       Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       parent
				__lowerCAmelCase      :  Optional[Any]												=       batch_size
				__lowerCAmelCase      :  Union[str, Any]												=       seq_length
				__lowerCAmelCase      :  Optional[Any]												=       is_training
				__lowerCAmelCase      :  Optional[int]												=       use_input_mask
				__lowerCAmelCase      :  Dict												=       use_token_type_ids
				__lowerCAmelCase      :  Dict												=       use_labels
				__lowerCAmelCase      :  Dict												=       vocab_size
				__lowerCAmelCase      :  Tuple												=       hidden_size
				__lowerCAmelCase      :  List[Any]												=       num_hidden_layers
				__lowerCAmelCase      :  Union[str, Any]												=       num_attention_heads
				__lowerCAmelCase      :  Tuple												=       intermediate_size
				__lowerCAmelCase      :  List[Any]												=       hidden_act
				__lowerCAmelCase      :  Optional[Any]												=       hidden_dropout_prob
				__lowerCAmelCase      :  Optional[Any]												=       attention_probs_dropout_prob
				__lowerCAmelCase      :  Optional[int]												=       max_position_embeddings
				__lowerCAmelCase      :  Union[str, Any]												=       type_vocab_size
				__lowerCAmelCase      :  Optional[int]												=       type_sequence_label_size
				__lowerCAmelCase      :  Dict												=       initializer_range
				__lowerCAmelCase      :  Tuple												=       num_labels
				__lowerCAmelCase      :  Optional[Any]												=       num_choices
				__lowerCAmelCase      :  Union[str, Any]												=       scope
				__lowerCAmelCase      :  Optional[Any]												=       q_groups
				__lowerCAmelCase      :  Optional[int]												=       k_groups
				__lowerCAmelCase      :  Any												=       v_groups
				__lowerCAmelCase      :  int												=       post_attention_groups
				__lowerCAmelCase      :  List[str]												=       intermediate_groups
				__lowerCAmelCase      :  Optional[Any]												=       output_groups

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       List[str]:

				"""simple docstring"""

				__lowerCAmelCase      :  str												=       ids_tensor([self.batch_size, self.seq_length]       ,			self.vocab_size)

				__lowerCAmelCase      :  Union[str, Any]												=       None
				if self.use_input_mask:
							__lowerCAmelCase      :  Tuple												=       random_attention_mask([self.batch_size, self.seq_length])

				__lowerCAmelCase      :  Optional[int]												=       None
				__lowerCAmelCase      :  List[Any]												=       None
				__lowerCAmelCase      :  str												=       None
				if self.use_labels:
							__lowerCAmelCase      :  Optional[int]												=       ids_tensor([self.batch_size]       ,			self.type_sequence_label_size)
							__lowerCAmelCase      :  str												=       ids_tensor([self.batch_size, self.seq_length]       ,			self.num_labels)
							__lowerCAmelCase      :  str												=       ids_tensor([self.batch_size]       ,			self.num_choices)

				__lowerCAmelCase      :  Any												=       self.get_config()

				return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple)				->       int:

				"""simple docstring"""

				return SqueezeBertConfig(
				    embedding_size=self.hidden_size       ,			vocab_size=self.vocab_size       ,			hidden_size=self.hidden_size       ,			num_hidden_layers=self.num_hidden_layers       ,			num_attention_heads=self.num_attention_heads       ,			intermediate_size=self.intermediate_size       ,			hidden_act=self.hidden_act       ,			attention_probs_dropout_prob=self.hidden_dropout_prob       ,			attention_dropout=self.attention_probs_dropout_prob       ,			max_position_embeddings=self.max_position_embeddings       ,			initializer_range=self.initializer_range       ,			q_groups=self.q_groups       ,			k_groups=self.k_groups       ,			v_groups=self.v_groups       ,			post_attention_groups=self.post_attention_groups       ,			intermediate_groups=self.intermediate_groups       ,			output_groups=self.output_groups       ,			)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple       ,			_SCREAMING_SNAKE_CASE:		List[str]       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Tuple       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Tuple)				->       Tuple:

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       SqueezeBertModel(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  List[Any]												=       model(_SCREAMING_SNAKE_CASE       ,			_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Dict												=       model(_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.last_hidden_state.shape       ,			(self.batch_size, self.seq_length, self.hidden_size))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		List[str]       ,			_SCREAMING_SNAKE_CASE:		str       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		int       ,			_SCREAMING_SNAKE_CASE:		Tuple)				->       Dict:

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       SqueezeBertForMaskedLM(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  Dict												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.vocab_size))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any])				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  str												=       SqueezeBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  Union[str, Any]												=       model(
				    _SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			start_positions=_SCREAMING_SNAKE_CASE       ,			end_positions=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.start_logits.shape       ,			(self.batch_size, self.seq_length))
				self.parent.assertEqual(result.end_logits.shape       ,			(self.batch_size, self.seq_length))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Tuple       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		Tuple)				->       Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       self.num_labels
				__lowerCAmelCase      :  Union[str, Any]												=       SqueezeBertForSequenceClassification(_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  int												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.num_labels))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Optional[int])				->       Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       self.num_labels
				__lowerCAmelCase      :  Optional[int]												=       SqueezeBertForTokenClassification(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()

				__lowerCAmelCase      :  List[str]												=       model(_SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.num_labels))

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Any       ,			_SCREAMING_SNAKE_CASE:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		int)				->       Tuple:

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       self.num_choices
				__lowerCAmelCase      :  str												=       SqueezeBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE)
				model.to(_SCREAMING_SNAKE_CASE)
				model.eval()
				__lowerCAmelCase      :  int												=       input_ids.unsqueeze(1).expand(-1       ,			self.num_choices       ,			-1).contiguous()
				__lowerCAmelCase      :  Union[str, Any]												=       input_mask.unsqueeze(1).expand(-1       ,			self.num_choices       ,			-1).contiguous()
				__lowerCAmelCase      :  str												=       model(
				    _SCREAMING_SNAKE_CASE       ,			attention_mask=_SCREAMING_SNAKE_CASE       ,			labels=_SCREAMING_SNAKE_CASE       ,			)
				self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.num_choices))







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

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[int]												=       self.prepare_config_and_inputs()
				((__lowerCAmelCase)						,	(__lowerCAmelCase)						,	(__lowerCAmelCase)						,	(__lowerCAmelCase)						,	(__lowerCAmelCase)						,	(__lowerCAmelCase))      :  Union[str, Any]												=       config_and_inputs
				__lowerCAmelCase      :  int												=       {"input_ids": input_ids, "attention_mask": input_mask}
				return config, inputs_dict






@require_torch
class 			A__   (  __SCREAMING_SNAKE_CASE  ,		__SCREAMING_SNAKE_CASE  ,		unittest.TestCase							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	(
	    (
	        SqueezeBertModel,
	        SqueezeBertForMaskedLM,
	        SqueezeBertForMultipleChoice,
	        SqueezeBertForQuestionAnswering,
	        SqueezeBertForSequenceClassification,
	        SqueezeBertForTokenClassification,
	    )
	    if is_torch_available()
	    else None
	)
	SCREAMING_SNAKE_CASE          =	(
	    {
	        'feature-extraction': SqueezeBertModel,
	        'fill-mask': SqueezeBertForMaskedLM,
	        'question-answering': SqueezeBertForQuestionAnswering,
	        'text-classification': SqueezeBertForSequenceClassification,
	        'token-classification': SqueezeBertForTokenClassification,
	        'zero-shot': SqueezeBertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE          =	False
	SCREAMING_SNAKE_CASE          =	True
	SCREAMING_SNAKE_CASE          =	False

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       SqueezeBertModelTester(self)
				__lowerCAmelCase      :  Optional[int]												=       ConfigTester(self       ,			config_class=_SCREAMING_SNAKE_CASE       ,			dim=37)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       Tuple:

				"""simple docstring"""

				self.config_tester.run_common_tests()

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[int])				->       Any:

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_model(*_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_masked_lm(*_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_question_answering(*_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		List[Any])				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  Tuple												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_token_classification(*_SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_squeezebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE)







	@slow
	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       Dict:

				"""simple docstring"""

				for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowerCAmelCase      :  Optional[Any]												=       SqueezeBertModel.from_pretrained(_SCREAMING_SNAKE_CASE)
							self.assertIsNotNone(_SCREAMING_SNAKE_CASE)






@require_sentencepiece
@require_tokenizers
@require_torch
class 			A__   (  unittest.TestCase							):




	'''simple docstring'''





	@slow
	def 							_SCREAMING_SNAKE_CASE   (     self:		int)				->       List[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[Any]												=       SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli")

				__lowerCAmelCase      :  List[Any]												=       torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]])
				__lowerCAmelCase      :  List[Any]												=       model(_SCREAMING_SNAKE_CASE)[0]
				__lowerCAmelCase      :  Any												=       torch.Size((1, 3))
				self.assertEqual(output.shape       ,			_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Union[str, Any]												=       torch.tensor([[0.6401, -0.0349, -0.6041]])
				self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE       ,			_SCREAMING_SNAKE_CASE       ,			atol=1e-4))