code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( 'files', [ ['full:README.md', 'dataset_infos.json'], ['empty:README.md', 'dataset_infos.json'], ['dataset_infos.json'], ['full:README.md'], ], ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('dset_infos_dir' ) if "full:README.md" in files: with open(dataset_infos_dir / 'README.md', 'w' ) as f: f.write('---\ndataset_info:\n dataset_size: 42\n---' ) if "empty:README.md" in files: with open(dataset_infos_dir / 'README.md', 'w' ) as f: f.write('' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / 'dataset_infos.json', 'w' ) as f: f.write('{"default": {"dataset_size": 42}}' ) SCREAMING_SNAKE_CASE =DatasetInfosDict.from_directory(lowerCAmelCase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( 'dataset_info', [ DatasetInfo(), DatasetInfo( description='foo', features=Features({'a': Value('int32' )} ), builder_name='builder', config_name='config', version='1.0.0', splits=[{'name': 'train'}], download_size=42, ), ], ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(lowerCAmelCase_ ) dataset_info.write_to_directory(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DatasetInfo.from_directory(lowerCAmelCase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowerCAmelCase_, 'dataset_info.json' ) ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =DatasetInfo( description='foo', citation='bar', homepage='https://foo.bar', license='CC0', features=Features({'a': Value('int32' )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name='builder', config_name='config', version='1.0.0', splits=[{'name': 'train', 'num_examples': 42}], download_checksums={}, download_size=1337, post_processing_size=442, dataset_size=1234, size_in_bytes=1337 + 442 + 1234, ) SCREAMING_SNAKE_CASE =dataset_info._to_yaml_dict() assert sorted(lowerCAmelCase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) ) SCREAMING_SNAKE_CASE =yaml.safe_dump(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =yaml.safe_load(lowerCAmelCase_ ) assert dataset_info_yaml_dict == reloaded def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =DatasetInfo() SCREAMING_SNAKE_CASE =dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( 'dataset_infos_dict', [ DatasetInfosDict(), DatasetInfosDict({'default': DatasetInfo()} ), DatasetInfosDict({'my_config_name': DatasetInfo()} ), DatasetInfosDict( { 'default': DatasetInfo( description='foo', features=Features({'a': Value('int32' )} ), builder_name='builder', config_name='config', version='1.0.0', splits=[{'name': 'train'}], download_size=42, ) } ), DatasetInfosDict( { 'v1': DatasetInfo(dataset_size=42 ), 'v2': DatasetInfo(dataset_size=1337 ), } ), ], ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(lowerCAmelCase_ ) dataset_infos_dict.write_to_directory(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DatasetInfosDict.from_directory(lowerCAmelCase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): SCREAMING_SNAKE_CASE =config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml SCREAMING_SNAKE_CASE =DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowerCAmelCase_, 'README.md' ) )
334
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 a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =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 =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =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(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) 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 , SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) 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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, '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 snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase ={ "configuration_trajectory_transformer": [ "TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrajectoryTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TrajectoryTransformerModel", "TrajectoryTransformerPreTrainedModel", "load_tf_weights_in_trajectory_transformer", ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 _lowerCamelCase =get_tests_dir("fixtures") _lowerCamelCase =get_tests_dir("fixtures/dummy_feature_extractor_config.json") _lowerCamelCase =get_tests_dir("fixtures/dummy-config.json") class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =0 def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h' ) self.assertIsInstance(snake_case ,snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ) self.assertIsInstance(snake_case ,snake_case ) def _lowerCAmelCase ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE =WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ).to_dict() config_dict.pop('feature_extractor_type' ) SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor(**snake_case ) # save in new folder model_config.save_pretrained(snake_case ) config.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ) # make sure private variable is not incorrectly saved SCREAMING_SNAKE_CASE =json.loads(config.to_json_string() ) self.assertTrue('_processor_class' not in dict_as_saved ) self.assertIsInstance(snake_case ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ) self.assertIsInstance(snake_case ,snake_case ) def _lowerCAmelCase ( self : Any ): with self.assertRaisesRegex( snake_case ,'bert-base is not a local folder and is not a valid model identifier' ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained('bert-base' ) def _lowerCAmelCase ( self : int ): with self.assertRaisesRegex( snake_case ,r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ,revision='aaaaaa' ) def _lowerCAmelCase ( self : Dict ): with self.assertRaisesRegex( snake_case ,'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.' ,): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model' ) def _lowerCAmelCase ( self : int ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ,trust_remote_code=snake_case ) SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ,trust_remote_code=snake_case ) self.assertEqual(feature_extractor.__class__.__name__ ,'NewFeatureExtractor' ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ,trust_remote_code=snake_case ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ ,'NewFeatureExtractor' ) def _lowerCAmelCase ( self : Union[str, Any] ): try: AutoConfig.register('custom' ,snake_case ) AutoFeatureExtractor.register(snake_case ,snake_case ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(snake_case ): AutoFeatureExtractor.register(snake_case ,snake_case ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE =CustomFeatureExtractor.from_pretrained(snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained(snake_case ) self.assertIsInstance(snake_case ,snake_case ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def _lowerCAmelCase ( self : Tuple ): class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = True try: AutoConfig.register('custom' ,snake_case ) AutoFeatureExtractor.register(snake_case ,snake_case ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ) self.assertEqual(feature_extractor.__class__.__name__ ,'NewFeatureExtractor' ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ,trust_remote_code=snake_case ) self.assertEqual(feature_extractor.__class__.__name__ ,'NewFeatureExtractor' ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( 'hf-internal-testing/test_dynamic_feature_extractor' ,trust_remote_code=snake_case ) self.assertEqual(feature_extractor.__class__.__name__ ,'NewFeatureExtractor' ) self.assertTrue(not hasattr(snake_case ,'is_local' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available _lowerCamelCase ={"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["HerbertTokenizerFast"] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version _lowerCamelCase =logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt") _lowerCamelCase =list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) _lowerCamelCase =tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'rb' ) as f: SCREAMING_SNAKE_CASE =Image.open(lowerCAmelCase_ ) return im.convert('RGB' ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={ 'help': 'Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).' } , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'A folder containing the training data.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'A folder containing the validation data.'} ) __UpperCAmelCase = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def _lowerCAmelCase ( self : Dict ): if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( 'You must specify either a dataset name from the hub or a train and/or validation directory.' ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='google/vit-base-patch16-224-in21k' , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(lowerCamelCase_ )} , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) __UpperCAmelCase = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Name or path of preprocessor config.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.stack([example['pixel_values'] for example in examples] ) SCREAMING_SNAKE_CASE =torch.tensor([example['labels'] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_image_classification', lowerCAmelCase_, lowerCAmelCase_ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', handlers=[logging.StreamHandler(sys.stdout )], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE =training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: SCREAMING_SNAKE_CASE =load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, task='image-classification', use_auth_token=True if model_args.use_auth_token else None, ) else: SCREAMING_SNAKE_CASE ={} if data_args.train_dir is not None: SCREAMING_SNAKE_CASE =os.path.join(data_args.train_dir, '**' ) if data_args.validation_dir is not None: SCREAMING_SNAKE_CASE =os.path.join(data_args.validation_dir, '**' ) SCREAMING_SNAKE_CASE =load_dataset( 'imagefolder', data_files=lowerCAmelCase_, cache_dir=model_args.cache_dir, task='image-classification', ) # If we don't have a validation split, split off a percentage of train as validation. SCREAMING_SNAKE_CASE =None if 'validation' in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split, lowerCAmelCase_ ) and data_args.train_val_split > 0.0: SCREAMING_SNAKE_CASE =dataset['train'].train_test_split(data_args.train_val_split ) SCREAMING_SNAKE_CASE =split['train'] SCREAMING_SNAKE_CASE =split['test'] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. SCREAMING_SNAKE_CASE =dataset['train'].features['labels'].names SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ={}, {} for i, label in enumerate(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =str(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =label # Load the accuracy metric from the datasets package SCREAMING_SNAKE_CASE =evaluate.load('accuracy' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(lowerCAmelCase_ ): return metric.compute(predictions=np.argmax(p.predictions, axis=1 ), references=p.label_ids ) SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path, num_labels=len(lowerCAmelCase_ ), labelaid=lowerCAmelCase_, idalabel=lowerCAmelCase_, finetuning_task='image-classification', cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) SCREAMING_SNAKE_CASE =AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool('.ckpt' in model_args.model_name_or_path ), config=lowerCAmelCase_, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ignore_mismatched_sizes=model_args.ignore_mismatched_sizes, ) SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: SCREAMING_SNAKE_CASE =image_processor.size['shortest_edge'] else: SCREAMING_SNAKE_CASE =(image_processor.size['height'], image_processor.size['width']) SCREAMING_SNAKE_CASE =Normalize(mean=image_processor.image_mean, std=image_processor.image_std ) SCREAMING_SNAKE_CASE =Compose( [ RandomResizedCrop(lowerCAmelCase_ ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) SCREAMING_SNAKE_CASE =Compose( [ Resize(lowerCAmelCase_ ), CenterCrop(lowerCAmelCase_ ), ToTensor(), normalize, ] ) def train_transforms(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =[ _train_transforms(pil_img.convert('RGB' ) ) for pil_img in example_batch['image'] ] return example_batch def val_transforms(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =[_val_transforms(pil_img.convert('RGB' ) ) for pil_img in example_batch['image']] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE =( dataset['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(lowerCAmelCase_ ) if training_args.do_eval: if "validation" not in dataset: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE =( dataset['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(lowerCAmelCase_ ) # Initalize our trainer SCREAMING_SNAKE_CASE =Trainer( model=lowerCAmelCase_, args=lowerCAmelCase_, train_dataset=dataset['train'] if training_args.do_train else None, eval_dataset=dataset['validation'] if training_args.do_eval else None, compute_metrics=lowerCAmelCase_, tokenizer=lowerCAmelCase_, data_collator=lowerCAmelCase_, ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE =None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE =training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE =last_checkpoint SCREAMING_SNAKE_CASE =trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() trainer.log_metrics('train', train_result.metrics ) trainer.save_metrics('train', train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: SCREAMING_SNAKE_CASE =trainer.evaluate() trainer.log_metrics('eval', lowerCAmelCase_ ) trainer.save_metrics('eval', lowerCAmelCase_ ) # Write model card and (optionally) push to hub SCREAMING_SNAKE_CASE ={ 'finetuned_from': model_args.model_name_or_path, 'tasks': 'image-classification', 'dataset': data_args.dataset_name, 'tags': ['image-classification', 'vision'], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) if __name__ == "__main__": main()
334
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_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =seq_length SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_input_mask SCREAMING_SNAKE_CASE =use_token_type_ids SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_choices SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Optional[int] ): 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 _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=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 _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=False, lowerCAmelCase_=False, lowerCAmelCase_=False ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'transformer.blocks.{i}.norm1.weight', F'vilt.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'transformer.blocks.{i}.norm1.bias', F'vilt.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'transformer.blocks.{i}.attn.proj.weight', F'vilt.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'transformer.blocks.{i}.attn.proj.bias', F'vilt.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'transformer.blocks.{i}.norm2.weight', F'vilt.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'transformer.blocks.{i}.norm2.bias', F'vilt.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append( (F'transformer.blocks.{i}.mlp.fc1.weight', F'vilt.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc1.bias', F'vilt.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc2.weight', F'vilt.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc2.bias', F'vilt.encoder.layer.{i}.output.dense.bias') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE ='vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE =state_dict.pop(F'transformer.blocks.{i}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE =state_dict.pop(F'transformer.blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE =in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE =in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE =in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE =in_proj_bias[-config.hidden_size :] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowerCAmelCase_, lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =dct.pop(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =val @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =ViltConfig(image_size=384, patch_size=32, tie_word_embeddings=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =3129 SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE ='vqa2-id2label.json' SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =ViltForQuestionAnswering(lowerCAmelCase_ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE ={0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE ={v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE =ViltForImagesAndTextClassification(lowerCAmelCase_ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =ViltForImageAndTextRetrieval(lowerCAmelCase_ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =ViltForMaskedLM(lowerCAmelCase_ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE =create_rename_keys(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) read_in_q_k_v(lowerCAmelCase_, lowerCAmelCase_ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE =['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowerCAmelCase_, lowerCAmelCase_ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =model.load_state_dict(lowerCAmelCase_, strict=lowerCAmelCase_ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowerCAmelCase_ ) # Define processor SCREAMING_SNAKE_CASE =ViltImageProcessor(size=384 ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE =ViltProcessor(lowerCAmelCase_, lowerCAmelCase_ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE =Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg', stream=lowerCAmelCase_ ).raw ) SCREAMING_SNAKE_CASE =Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg', stream=lowerCAmelCase_ ).raw ) SCREAMING_SNAKE_CASE =( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE =processor(lowerCAmelCase_, lowerCAmelCase_, return_tensors='pt' ) SCREAMING_SNAKE_CASE =processor(lowerCAmelCase_, lowerCAmelCase_, return_tensors='pt' ) SCREAMING_SNAKE_CASE =model( input_ids=encoding_a.input_ids, pixel_values=encoding_a.pixel_values, pixel_values_a=encoding_a.pixel_values, ) else: SCREAMING_SNAKE_CASE =Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg', stream=lowerCAmelCase_ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE ='a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE ='How many cats are there?' SCREAMING_SNAKE_CASE =processor(lowerCAmelCase_, lowerCAmelCase_, return_tensors='pt' ) SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE =torch.Size([1, 11, 30522] ) SCREAMING_SNAKE_CASE =torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3], lowerCAmelCase_, atol=1e-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE =outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE =torch.Size([1, 3129] ) SCREAMING_SNAKE_CASE =torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3], lowerCAmelCase_, atol=1e-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3], lowerCAmelCase_, atol=1e-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE =outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE =torch.Size([1, 2] ) SCREAMING_SNAKE_CASE =torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3], lowerCAmelCase_, atol=1e-4 ) assert outputs.logits.shape == expected_shape Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F'Saving model and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) _lowerCamelCase =parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class a_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : List[str] ,snake_case : Dict[str, int] ,snake_case : List[str] ,snake_case : int = None ,snake_case : int = None ): super().__init__() SCREAMING_SNAKE_CASE =pad_token_id SCREAMING_SNAKE_CASE =max_length SCREAMING_SNAKE_CASE =vocab SCREAMING_SNAKE_CASE =merges SCREAMING_SNAKE_CASE =BytePairTokenizer(snake_case ,snake_case ,sequence_length=snake_case ) @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : GPTaTokenizer ,*snake_case : List[str] ,**snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =[' '.join(snake_case ) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE =tokenizer.get_vocab() return cls(snake_case ,snake_case ,*snake_case ,**snake_case ) @classmethod def _lowerCAmelCase ( cls : Optional[Any] ,snake_case : Union[str, os.PathLike] ,*snake_case : Optional[int] ,**snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =GPTaTokenizer.from_pretrained(snake_case ,*snake_case ,**snake_case ) return cls.from_tokenizer(snake_case ,*snake_case ,**snake_case ) @classmethod def _lowerCAmelCase ( cls : Any ,snake_case : List[Any] ): return cls(**snake_case ) def _lowerCAmelCase ( self : Any ): return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _lowerCAmelCase ( self : Dict ,snake_case : Any ,snake_case : int = None ): SCREAMING_SNAKE_CASE =self.tf_tokenizer(snake_case ) SCREAMING_SNAKE_CASE =tf.ones_like(snake_case ) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE =max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =pad_model_inputs( snake_case ,max_seq_length=snake_case ,pad_value=self.pad_token_id ) return {"attention_mask": attention_mask, "input_ids": input_ids}
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class a_ : """simple docstring""" def __init__( self : List[Any] ,snake_case : str ,snake_case : Union[str, Any]=13 ,snake_case : Optional[int]=7 ,snake_case : Dict=True ,snake_case : str=True ,snake_case : str=False ,snake_case : List[str]=True ,snake_case : str=99 ,snake_case : str=32 ,snake_case : Union[str, Any]=5 ,snake_case : Dict=4 ,snake_case : Dict=37 ,snake_case : Tuple="gelu" ,snake_case : List[str]=0.1 ,snake_case : Optional[int]=0.1 ,snake_case : List[str]=512 ,snake_case : Tuple=16 ,snake_case : str=2 ,snake_case : List[Any]=0.02 ,snake_case : Dict=3 ,snake_case : Dict=4 ,snake_case : int=None ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =seq_length SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_input_mask SCREAMING_SNAKE_CASE =use_token_type_ids SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_choices SCREAMING_SNAKE_CASE =scope def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : List[Any] ): return OpenLlamaConfig( 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 ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=snake_case ,initializer_range=self.initializer_range ,use_stable_embedding=snake_case ,) def _lowerCAmelCase ( self : int ,snake_case : str ,snake_case : List[Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Tuple ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =OpenLlamaModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : int ,snake_case : List[str] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : Any ,snake_case : str ,snake_case : List[str] ,snake_case : Tuple ,snake_case : int ,snake_case : Dict ,): SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =OpenLlamaModel(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,encoder_hidden_states=snake_case ,encoder_attention_mask=snake_case ,) SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,encoder_hidden_states=snake_case ,) SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : str ,snake_case : List[Any] ,snake_case : Optional[int] ,snake_case : Optional[Any] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,): SCREAMING_SNAKE_CASE =OpenLlamaForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Any ,snake_case : Optional[Any] ,snake_case : int ,snake_case : str ,snake_case : Dict ,snake_case : Dict ,snake_case : Dict ,snake_case : str ,snake_case : List[Any] ,snake_case : List[str] ,): SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =OpenLlamaForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() # first forward pass SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,encoder_hidden_states=snake_case ,encoder_attention_mask=snake_case ,use_cache=snake_case ,) SCREAMING_SNAKE_CASE =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 3) ,config.vocab_size ) SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE =torch.cat([input_ids, next_tokens] ,dim=-1 ) SCREAMING_SNAKE_CASE =torch.cat([input_mask, next_mask] ,dim=-1 ) SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,encoder_hidden_states=snake_case ,encoder_attention_mask=snake_case ,output_hidden_states=snake_case ,)['hidden_states'][0] SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,encoder_hidden_states=snake_case ,encoder_attention_mask=snake_case ,past_key_values=snake_case ,output_hidden_states=snake_case ,)['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE =ids_tensor((1,) ,output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE =output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-3 ) ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) __UpperCAmelCase = (OpenLlamaForCausalLM,) if is_torch_available() else () __UpperCAmelCase = ( { 'feature-extraction': OpenLlamaModel, 'text-classification': OpenLlamaForSequenceClassification, 'text-generation': OpenLlamaForCausalLM, 'zero-shot': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =OpenLlamaModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : Dict ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE =type self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE =input_dict['input_ids'] SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(snake_case ) SCREAMING_SNAKE_CASE =ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE =OpenLlamaForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE ='single_label_classification' SCREAMING_SNAKE_CASE =input_dict['input_ids'] SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(snake_case ) SCREAMING_SNAKE_CASE =ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE =OpenLlamaForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE ='multi_label_classification' SCREAMING_SNAKE_CASE =input_dict['input_ids'] SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(snake_case ) SCREAMING_SNAKE_CASE =ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE =OpenLlamaForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def _lowerCAmelCase ( self : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =ids_tensor([1, 10] ,config.vocab_size ) SCREAMING_SNAKE_CASE =ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE =OpenLlamaModel(snake_case ) original_model.to(snake_case ) original_model.eval() SCREAMING_SNAKE_CASE =original_model(snake_case ).last_hidden_state SCREAMING_SNAKE_CASE =original_model(snake_case ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE ={'type': scaling_type, 'factor': 10.0} SCREAMING_SNAKE_CASE =OpenLlamaModel(snake_case ) scaled_model.to(snake_case ) scaled_model.eval() SCREAMING_SNAKE_CASE =scaled_model(snake_case ).last_hidden_state SCREAMING_SNAKE_CASE =scaled_model(snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(snake_case ,snake_case ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(snake_case ,snake_case ,atol=1e-5 ) )
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) SCREAMING_SNAKE_CASE ='xvjiarui/stable-diffusion-2-inpainting' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =FlaxStableDiffusionInpaintPipeline.from_pretrained(snake_case ,safety_checker=snake_case ) SCREAMING_SNAKE_CASE ='Face of a yellow cat, high resolution, sitting on a park bench' SCREAMING_SNAKE_CASE =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE =50 SCREAMING_SNAKE_CASE =jax.device_count() SCREAMING_SNAKE_CASE =num_samples * [prompt] SCREAMING_SNAKE_CASE =num_samples * [init_image] SCREAMING_SNAKE_CASE =num_samples * [mask_image] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =pipeline.prepare_inputs(snake_case ,snake_case ,snake_case ) # shard inputs and rng SCREAMING_SNAKE_CASE =replicate(snake_case ) SCREAMING_SNAKE_CASE =jax.random.split(snake_case ,jax.device_count() ) SCREAMING_SNAKE_CASE =shard(snake_case ) SCREAMING_SNAKE_CASE =shard(snake_case ) SCREAMING_SNAKE_CASE =shard(snake_case ) SCREAMING_SNAKE_CASE =pipeline( snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,jit=snake_case ) SCREAMING_SNAKE_CASE =output.images.reshape(snake_case ,512 ,512 ,3 ) SCREAMING_SNAKE_CASE =images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE =jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE =jnp.array( [0.3_611_307, 0.37_649_736, 0.3_757_408, 0.38_213_953, 0.39_295_167, 0.3_841_631, 0.41_554_978, 0.4_137_475, 0.4_217_084] ) print(f'output_slice: {output_slice}' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase ={ "configuration_convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig", "ConvNextOnnxConfig"] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["ConvNextFeatureExtractor"] _lowerCamelCase =["ConvNextImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure)
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCamelCase =logging.getLogger(__name__) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Whether tp freeze the encoder.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Whether to freeze the embeddings.'} ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} ) __UpperCAmelCase = field( default='summarization' , metadata={'help': 'Task name, summarization (or summarization_{dataset} for pegasus) or translation'} , ) __UpperCAmelCase = field( default=1_024 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase = field( default=128 , metadata={ 'help': ( 'The maximum total sequence length for target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase = field( default=142 , metadata={ 'help': ( 'The maximum total sequence length for validation target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded. ' 'This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ' 'during ``evaluate`` and ``predict``.' ) } , ) __UpperCAmelCase = field( default=142 , metadata={ 'help': ( 'The maximum total sequence length for test target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __UpperCAmelCase = field(default=-1 , metadata={'help': '# training examples. -1 means use all.'} ) __UpperCAmelCase = field(default=-1 , metadata={'help': '# validation examples. -1 means use all.'} ) __UpperCAmelCase = field(default=-1 , metadata={'help': '# test examples. -1 means use all.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Source language id for translation.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Target language id for translation.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': '# num_beams to use for evaluation.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'} , ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" logger.info(F'***** {split} metrics *****' ) for key in sorted(metrics.keys() ): logger.info(F' {key} = {metrics[key]}' ) save_json(lowerCAmelCase_, os.path.join(lowerCAmelCase_, F'{split}_results.json' ) ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() check_output_dir(lowerCAmelCase_ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ), training_args.fpaa, ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s', lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE =('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): assert hasattr(lowerCAmelCase_, lowerCAmelCase_ ), F'({config.__class__.__name__}) doesn\'t have a `{p}` attribute' setattr(lowerCAmelCase_, lowerCAmelCase_, getattr(lowerCAmelCase_, lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE =AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path, from_tf='.ckpt' in model_args.model_name_or_path, config=lowerCAmelCase_, cache_dir=model_args.cache_dir, ) # use task specific params use_task_specific_params(lowerCAmelCase_, data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: SCREAMING_SNAKE_CASE =model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(lowerCAmelCase_, (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =tokenizer.lang_code_to_id[data_args.tgt_lang] else: SCREAMING_SNAKE_CASE =tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(lowerCAmelCase_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) SCREAMING_SNAKE_CASE =SeqaSeqDataset # Get datasets SCREAMING_SNAKE_CASE =( dataset_class( lowerCAmelCase_, type_path='train', data_dir=data_args.data_dir, n_obs=data_args.n_train, max_target_length=data_args.max_target_length, max_source_length=data_args.max_source_length, prefix=model.config.prefix or '', ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE =( dataset_class( lowerCAmelCase_, type_path='val', data_dir=data_args.data_dir, n_obs=data_args.n_val, max_target_length=data_args.val_max_target_length, max_source_length=data_args.max_source_length, prefix=model.config.prefix or '', ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) SCREAMING_SNAKE_CASE =( dataset_class( lowerCAmelCase_, type_path='test', data_dir=data_args.data_dir, n_obs=data_args.n_test, max_target_length=data_args.test_max_target_length, max_source_length=data_args.max_source_length, prefix=model.config.prefix or '', ) if training_args.do_predict else None ) # Initialize our Trainer SCREAMING_SNAKE_CASE =( build_compute_metrics_fn(data_args.task, lowerCAmelCase_ ) if training_args.predict_with_generate else None ) SCREAMING_SNAKE_CASE =SeqaSeqTrainer( model=lowerCAmelCase_, args=lowerCAmelCase_, data_args=lowerCAmelCase_, train_dataset=lowerCAmelCase_, eval_dataset=lowerCAmelCase_, data_collator=SeqaSeqDataCollator( lowerCAmelCase_, lowerCAmelCase_, model.config.decoder_start_token_id, training_args.tpu_num_cores ), compute_metrics=lowerCAmelCase_, tokenizer=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE ={} # Training if training_args.do_train: logger.info('*** Train ***' ) SCREAMING_SNAKE_CASE =trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) SCREAMING_SNAKE_CASE =train_result.metrics SCREAMING_SNAKE_CASE =data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('train', lowerCAmelCase_, training_args.output_dir ) all_metrics.update(lowerCAmelCase_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir, 'trainer_state.json' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) SCREAMING_SNAKE_CASE =trainer.evaluate(metric_key_prefix='val' ) SCREAMING_SNAKE_CASE =data_args.n_val SCREAMING_SNAKE_CASE =round(metrics['val_loss'], 4 ) if trainer.is_world_process_zero(): handle_metrics('val', lowerCAmelCase_, training_args.output_dir ) all_metrics.update(lowerCAmelCase_ ) if training_args.do_predict: logger.info('*** Predict ***' ) SCREAMING_SNAKE_CASE =trainer.predict(test_dataset=lowerCAmelCase_, metric_key_prefix='test' ) SCREAMING_SNAKE_CASE =test_output.metrics SCREAMING_SNAKE_CASE =data_args.n_test if trainer.is_world_process_zero(): SCREAMING_SNAKE_CASE =round(metrics['test_loss'], 4 ) handle_metrics('test', lowerCAmelCase_, training_args.output_dir ) all_metrics.update(lowerCAmelCase_ ) if training_args.predict_with_generate: SCREAMING_SNAKE_CASE =tokenizer.batch_decode( test_output.predictions, skip_special_tokens=lowerCAmelCase_, clean_up_tokenization_spaces=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =lmap(str.strip, lowerCAmelCase_ ) write_txt_file(lowerCAmelCase_, os.path.join(training_args.output_dir, 'test_generations.txt' ) ) if trainer.is_world_process_zero(): save_json(lowerCAmelCase_, os.path.join(training_args.output_dir, 'all_results.json' ) ) return all_metrics def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" main() if __name__ == "__main__": main()
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Optional[Any] ,snake_case : Any ,snake_case : Dict ): SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =graph self._normalize_graph(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =len(snake_case ) SCREAMING_SNAKE_CASE =None def _lowerCAmelCase ( self : List[str] ,snake_case : List[str] ,snake_case : Union[str, Any] ): if sources is int: SCREAMING_SNAKE_CASE =[sources] if sinks is int: SCREAMING_SNAKE_CASE =[sinks] if len(snake_case ) == 0 or len(snake_case ) == 0: return SCREAMING_SNAKE_CASE =sources[0] SCREAMING_SNAKE_CASE =sinks[0] # make fake vertex if there are more # than one source or sink if len(snake_case ) > 1 or len(snake_case ) > 1: SCREAMING_SNAKE_CASE =0 for i in sources: max_input_flow += sum(self.graph[i] ) SCREAMING_SNAKE_CASE =len(self.graph ) + 1 for room in self.graph: room.insert(0 ,0 ) self.graph.insert(0 ,[0] * size ) for i in sources: SCREAMING_SNAKE_CASE =max_input_flow SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: SCREAMING_SNAKE_CASE =max_input_flow SCREAMING_SNAKE_CASE =size - 1 def _lowerCAmelCase ( self : Optional[int] ): if self.maximum_flow_algorithm is None: raise Exception('You need to set maximum flow algorithm before.' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def _lowerCAmelCase ( self : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =algorithm(self ) class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =flow_network SCREAMING_SNAKE_CASE =flow_network.verticesCount SCREAMING_SNAKE_CASE =flow_network.sourceIndex SCREAMING_SNAKE_CASE =flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that SCREAMING_SNAKE_CASE =flow_network.graph SCREAMING_SNAKE_CASE =False def _lowerCAmelCase ( self : str ): if not self.executed: self._algorithm() SCREAMING_SNAKE_CASE =True def _lowerCAmelCase ( self : str ): pass class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] ,snake_case : List[Any] ): super().__init__(snake_case ) # use this to save your result SCREAMING_SNAKE_CASE =-1 def _lowerCAmelCase ( self : Dict ): if not self.executed: raise Exception('You should execute algorithm before using its result!' ) return self.maximum_flow class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] ,snake_case : Dict ): super().__init__(snake_case ) SCREAMING_SNAKE_CASE =[[0] * self.verticies_count for i in range(self.verticies_count )] SCREAMING_SNAKE_CASE =[0] * self.verticies_count SCREAMING_SNAKE_CASE =[0] * self.verticies_count def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule SCREAMING_SNAKE_CASE =[ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list SCREAMING_SNAKE_CASE =0 while i < len(snake_case ): SCREAMING_SNAKE_CASE =vertices_list[i] SCREAMING_SNAKE_CASE =self.heights[vertex_index] self.process_vertex(snake_case ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 ,vertices_list.pop(snake_case ) ) SCREAMING_SNAKE_CASE =0 else: i += 1 SCREAMING_SNAKE_CASE =sum(self.preflow[self.source_index] ) def _lowerCAmelCase ( self : Dict ,snake_case : Union[str, Any] ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(snake_case ,snake_case ) self.relabel(snake_case ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : Dict ): SCREAMING_SNAKE_CASE =min( self.excesses[from_index] ,self.graph[from_index][to_index] - self.preflow[from_index][to_index] ,) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def _lowerCAmelCase ( self : List[Any] ,snake_case : Any ): SCREAMING_SNAKE_CASE =None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): SCREAMING_SNAKE_CASE =self.heights[to_index] if min_height is not None: SCREAMING_SNAKE_CASE =min_height + 1 if __name__ == "__main__": _lowerCamelCase =[0] _lowerCamelCase =[3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] _lowerCamelCase =[[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network _lowerCamelCase =FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate _lowerCamelCase =flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,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 ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =config_and_inputs SCREAMING_SNAKE_CASE ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) SCREAMING_SNAKE_CASE =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE =['pixel_values'] self.assertListEqual(arg_names[:1] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput _lowerCamelCase =8 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=BITS ): """simple docstring""" SCREAMING_SNAKE_CASE =x.device SCREAMING_SNAKE_CASE =(x * 255).int().clamp(0, 255 ) SCREAMING_SNAKE_CASE =2 ** torch.arange(bits - 1, -1, -1, device=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =rearrange(lowerCAmelCase_, 'd -> d 1 1' ) SCREAMING_SNAKE_CASE =rearrange(lowerCAmelCase_, 'b c h w -> b c 1 h w' ) SCREAMING_SNAKE_CASE =((x & mask) != 0).float() SCREAMING_SNAKE_CASE =rearrange(lowerCAmelCase_, 'b c d h w -> b (c d) h w' ) SCREAMING_SNAKE_CASE =bits * 2 - 1 return bits def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=BITS ): """simple docstring""" SCREAMING_SNAKE_CASE =x.device SCREAMING_SNAKE_CASE =(x > 0).int() SCREAMING_SNAKE_CASE =2 ** torch.arange(bits - 1, -1, -1, device=lowerCAmelCase_, dtype=torch.intaa ) SCREAMING_SNAKE_CASE =rearrange(lowerCAmelCase_, 'd -> d 1 1' ) SCREAMING_SNAKE_CASE =rearrange(lowerCAmelCase_, 'b (c d) h w -> b c d h w', d=8 ) SCREAMING_SNAKE_CASE =reduce(x * mask, 'b c d h w -> b c h w', 'sum' ) return (dec / 255).clamp(0.0, 1.0 ) def snake_case__ ( self, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = 0.0, lowerCAmelCase_ = True, lowerCAmelCase_=None, lowerCAmelCase_ = True, ): """simple docstring""" if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) SCREAMING_SNAKE_CASE =timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas SCREAMING_SNAKE_CASE =self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE =self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod SCREAMING_SNAKE_CASE =1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE =(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" SCREAMING_SNAKE_CASE =self.bit_scale if self.config.clip_sample: SCREAMING_SNAKE_CASE =torch.clamp(lowerCAmelCase_, -scale, lowerCAmelCase_ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) SCREAMING_SNAKE_CASE =self._get_variance(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide SCREAMING_SNAKE_CASE =(sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE =(1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE =alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 SCREAMING_SNAKE_CASE =model_output.device if torch.is_tensor(lowerCAmelCase_ ) else 'cpu' SCREAMING_SNAKE_CASE =torch.randn(model_output.shape, dtype=model_output.dtype, generator=lowerCAmelCase_ ).to(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =self._get_variance(lowerCAmelCase_, lowerCAmelCase_ ) ** 0.5 * eta * noise SCREAMING_SNAKE_CASE =prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=lowerCAmelCase_, pred_original_sample=lowerCAmelCase_ ) def snake_case__ ( self, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_="epsilon", lowerCAmelCase_=None, lowerCAmelCase_ = True, ): """simple docstring""" SCREAMING_SNAKE_CASE =timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =torch.split(lowerCAmelCase_, sample.shape[1], dim=1 ) else: SCREAMING_SNAKE_CASE =None # 1. compute alphas, betas SCREAMING_SNAKE_CASE =self.alphas_cumprod[t] SCREAMING_SNAKE_CASE =self.alphas_cumprod[t - 1] if t > 0 else self.one SCREAMING_SNAKE_CASE =1 - alpha_prod_t SCREAMING_SNAKE_CASE =1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": SCREAMING_SNAKE_CASE =(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": SCREAMING_SNAKE_CASE =model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" SCREAMING_SNAKE_CASE =self.bit_scale if self.config.clip_sample: SCREAMING_SNAKE_CASE =torch.clamp(lowerCAmelCase_, -scale, lowerCAmelCase_ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf SCREAMING_SNAKE_CASE =(alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t SCREAMING_SNAKE_CASE =self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf SCREAMING_SNAKE_CASE =pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise SCREAMING_SNAKE_CASE =0 if t > 0: SCREAMING_SNAKE_CASE =torch.randn( model_output.size(), dtype=model_output.dtype, layout=model_output.layout, generator=lowerCAmelCase_ ).to(model_output.device ) SCREAMING_SNAKE_CASE =(self._get_variance(lowerCAmelCase_, predicted_variance=lowerCAmelCase_ ) ** 0.5) * noise SCREAMING_SNAKE_CASE =pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=lowerCAmelCase_, pred_original_sample=lowerCAmelCase_ ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : int ,snake_case : UNetaDConditionModel ,snake_case : Union[DDIMScheduler, DDPMScheduler] ,snake_case : Optional[float] = 1.0 ,): super().__init__() SCREAMING_SNAKE_CASE =bit_scale SCREAMING_SNAKE_CASE =( ddim_bit_scheduler_step if isinstance(snake_case ,snake_case ) else ddpm_bit_scheduler_step ) self.register_modules(unet=snake_case ,scheduler=snake_case ) @torch.no_grad() def __call__( self : List[Any] ,snake_case : Optional[int] = 256 ,snake_case : Optional[int] = 256 ,snake_case : Optional[int] = 50 ,snake_case : Optional[torch.Generator] = None ,snake_case : Optional[int] = 1 ,snake_case : Optional[str] = "pil" ,snake_case : bool = True ,**snake_case : str ,): SCREAMING_SNAKE_CASE =torch.randn( (batch_size, self.unet.config.in_channels, height, width) ,generator=snake_case ,) SCREAMING_SNAKE_CASE =decimal_to_bits(snake_case ) * self.bit_scale SCREAMING_SNAKE_CASE =latents.to(self.device ) self.scheduler.set_timesteps(snake_case ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual SCREAMING_SNAKE_CASE =self.unet(snake_case ,snake_case ).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE =self.scheduler.step(snake_case ,snake_case ,snake_case ).prev_sample SCREAMING_SNAKE_CASE =bits_to_decimal(snake_case ) if output_type == "pil": SCREAMING_SNAKE_CASE =self.numpy_to_pil(snake_case ) if not return_dict: return (image,) return ImagePipelineOutput(images=snake_case )
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowerCamelCase ={ "configuration_vivit": ["VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "VivitConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["VivitImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "VivitModel", "VivitPreTrainedModel", "VivitForVideoClassification", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE =load_dataset('glue', 'mrpc' ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowerCAmelCase_, max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE =datasets.map( lowerCAmelCase_, batched=lowerCAmelCase_, remove_columns=['idx', 'sentence1', 'sentence2'], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE =16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE =8 else: SCREAMING_SNAKE_CASE =None return tokenizer.pad( lowerCAmelCase_, padding='longest', max_length=lowerCAmelCase_, pad_to_multiple_of=lowerCAmelCase_, return_tensors='pt', ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['train'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['validation'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if os.environ.get('TESTING_MOCKED_DATALOADERS', lowerCAmelCase_ ) == "1": SCREAMING_SNAKE_CASE =2 # Initialize accelerator SCREAMING_SNAKE_CASE =Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE =config['lr'] SCREAMING_SNAKE_CASE =int(config['num_epochs'] ) SCREAMING_SNAKE_CASE =int(config['seed'] ) SCREAMING_SNAKE_CASE =int(config['batch_size'] ) SCREAMING_SNAKE_CASE =evaluate.load('glue', 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE =AutoModelForSequenceClassification.from_pretrained('bert-base-cased', return_dict=lowerCAmelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE =model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE =AdamW(params=model.parameters(), lr=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =get_dataloaders(lowerCAmelCase_, lowerCAmelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE =get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_, num_warmup_steps=100, num_training_steps=(len(lowerCAmelCase_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.prepare( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCAmelCase_, references=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:', lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision', type=lowerCAmelCase_, default=lowerCAmelCase_, choices=['no', 'fp16', 'bf16', 'fp8'], help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.', ) parser.add_argument('--cpu', action='store_true', help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE ={'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCAmelCase_, lowerCAmelCase_ ) if __name__ == "__main__": main()
334
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class a_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Any ,snake_case : Optional[int] ,snake_case : List[str]=7 ,snake_case : Any=3 ,snake_case : Tuple=18 ,snake_case : List[str]=30 ,snake_case : int=400 ,snake_case : Tuple=True ,snake_case : List[Any]=32 ,snake_case : Tuple=True ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =min_resolution SCREAMING_SNAKE_CASE =max_resolution SCREAMING_SNAKE_CASE =do_resize SCREAMING_SNAKE_CASE =size_divisor SCREAMING_SNAKE_CASE =do_rescale def _lowerCAmelCase ( self : Optional[int] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = GLPNImageProcessor if is_vision_available() else None def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =GLPNImageProcessingTester(self ) @property def _lowerCAmelCase ( self : str ): return self.image_processor_tester.prepare_image_processor_dict() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case ,'do_resize' ) ) self.assertTrue(hasattr(snake_case ,'size_divisor' ) ) self.assertTrue(hasattr(snake_case ,'resample' ) ) self.assertTrue(hasattr(snake_case ,'do_rescale' ) ) def _lowerCAmelCase ( self : Dict ): pass def _lowerCAmelCase ( self : Optional[int] ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def _lowerCAmelCase ( self : Union[str, Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,numpify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def _lowerCAmelCase ( self : Union[str, Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = FlaxAutoencoderKL @property def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE =(32, 32) SCREAMING_SNAKE_CASE =jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE =jax.random.uniform(snake_case ,((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE ={ 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } SCREAMING_SNAKE_CASE =self.dummy_input return init_dict, inputs_dict
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "SCUT-DLVCLab/lilt-roberta-en-base": ( "https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json" ), } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'lilt' def __init__( self : Union[str, Any] ,snake_case : Optional[Any]=30522 ,snake_case : Optional[int]=768 ,snake_case : int=12 ,snake_case : Tuple=12 ,snake_case : Union[str, Any]=3072 ,snake_case : Optional[int]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : Union[str, Any]=2 ,snake_case : List[str]=0.02 ,snake_case : Optional[int]=1e-12 ,snake_case : int=0 ,snake_case : Optional[Any]="absolute" ,snake_case : str=None ,snake_case : List[Any]=4 ,snake_case : Dict=1024 ,**snake_case : Optional[int] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =classifier_dropout SCREAMING_SNAKE_CASE =channel_shrink_ratio SCREAMING_SNAKE_CASE =max_ad_position_embeddings
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) for i in range(n - 1 ): for j in range(i + 1, lowerCAmelCase_ ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return arr, 0 SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) // 2 SCREAMING_SNAKE_CASE =arr[0:mid] SCREAMING_SNAKE_CASE =arr[mid:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =count_inversions_recursive(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =count_inversions_recursive(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =_count_cross_inversions(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =inversion_p + inversions_q + cross_inversions return c, num_inversions def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =SCREAMING_SNAKE_CASE =SCREAMING_SNAKE_CASE =0 while i < len(lowerCAmelCase_ ) and j < len(lowerCAmelCase_ ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(lowerCAmelCase_ ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(lowerCAmelCase_ ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =[10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) SCREAMING_SNAKE_CASE =count_inversions_bf(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =count_inversions_recursive(lowerCAmelCase_ ) assert num_inversions_bf == num_inversions_recursive == 8 print('number of inversions = ', lowerCAmelCase_ ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() SCREAMING_SNAKE_CASE =count_inversions_bf(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =count_inversions_recursive(lowerCAmelCase_ ) assert num_inversions_bf == num_inversions_recursive == 0 print('number of inversions = ', lowerCAmelCase_ ) # an empty list should also have zero inversions SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =count_inversions_bf(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =count_inversions_recursive(lowerCAmelCase_ ) assert num_inversions_bf == num_inversions_recursive == 0 print('number of inversions = ', lowerCAmelCase_ ) if __name__ == "__main__": main()
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 42 class a_ ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" @register_to_config def __init__( self : int ,snake_case : int = 65536 ,snake_case : Optional[int] = None ,snake_case : int = 2 ,snake_case : int = 2 ,snake_case : int = 0 ,snake_case : str = "fourier" ,snake_case : bool = True ,snake_case : bool = False ,snake_case : float = 0.0 ,snake_case : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") ,snake_case : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") ,snake_case : Tuple[str] = "UNetMidBlock1D" ,snake_case : str = None ,snake_case : Tuple[int] = (32, 32, 64) ,snake_case : str = None ,snake_case : int = 8 ,snake_case : int = 1 ,snake_case : bool = False ,): super().__init__() SCREAMING_SNAKE_CASE =sample_size # time if time_embedding_type == "fourier": SCREAMING_SNAKE_CASE =GaussianFourierProjection( embedding_size=8 ,set_W_to_weight=snake_case ,log=snake_case ,flip_sin_to_cos=snake_case ) SCREAMING_SNAKE_CASE =2 * block_out_channels[0] elif time_embedding_type == "positional": SCREAMING_SNAKE_CASE =Timesteps( block_out_channels[0] ,flip_sin_to_cos=snake_case ,downscale_freq_shift=snake_case ) SCREAMING_SNAKE_CASE =block_out_channels[0] if use_timestep_embedding: SCREAMING_SNAKE_CASE =block_out_channels[0] * 4 SCREAMING_SNAKE_CASE =TimestepEmbedding( in_channels=snake_case ,time_embed_dim=snake_case ,act_fn=snake_case ,out_dim=block_out_channels[0] ,) SCREAMING_SNAKE_CASE =nn.ModuleList([] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =nn.ModuleList([] ) SCREAMING_SNAKE_CASE =None # down SCREAMING_SNAKE_CASE =in_channels for i, down_block_type in enumerate(snake_case ): SCREAMING_SNAKE_CASE =output_channel SCREAMING_SNAKE_CASE =block_out_channels[i] if i == 0: input_channel += extra_in_channels SCREAMING_SNAKE_CASE =i == len(snake_case ) - 1 SCREAMING_SNAKE_CASE =get_down_block( snake_case ,num_layers=snake_case ,in_channels=snake_case ,out_channels=snake_case ,temb_channels=block_out_channels[0] ,add_downsample=not is_final_block or downsample_each_block ,) self.down_blocks.append(snake_case ) # mid SCREAMING_SNAKE_CASE =get_mid_block( snake_case ,in_channels=block_out_channels[-1] ,mid_channels=block_out_channels[-1] ,out_channels=block_out_channels[-1] ,embed_dim=block_out_channels[0] ,num_layers=snake_case ,add_downsample=snake_case ,) # up SCREAMING_SNAKE_CASE =list(reversed(snake_case ) ) SCREAMING_SNAKE_CASE =reversed_block_out_channels[0] if out_block_type is None: SCREAMING_SNAKE_CASE =out_channels else: SCREAMING_SNAKE_CASE =block_out_channels[0] for i, up_block_type in enumerate(snake_case ): SCREAMING_SNAKE_CASE =output_channel SCREAMING_SNAKE_CASE =( reversed_block_out_channels[i + 1] if i < len(snake_case ) - 1 else final_upsample_channels ) SCREAMING_SNAKE_CASE =i == len(snake_case ) - 1 SCREAMING_SNAKE_CASE =get_up_block( snake_case ,num_layers=snake_case ,in_channels=snake_case ,out_channels=snake_case ,temb_channels=block_out_channels[0] ,add_upsample=not is_final_block ,) self.up_blocks.append(snake_case ) SCREAMING_SNAKE_CASE =output_channel # out SCREAMING_SNAKE_CASE =norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 ,32 ) SCREAMING_SNAKE_CASE =get_out_block( out_block_type=snake_case ,num_groups_out=snake_case ,embed_dim=block_out_channels[0] ,out_channels=snake_case ,act_fn=snake_case ,fc_dim=block_out_channels[-1] // 4 ,) def _lowerCAmelCase ( self : Any ,snake_case : torch.FloatTensor ,snake_case : Union[torch.Tensor, float, int] ,snake_case : bool = True ,): SCREAMING_SNAKE_CASE =timestep if not torch.is_tensor(snake_case ): SCREAMING_SNAKE_CASE =torch.tensor([timesteps] ,dtype=torch.long ,device=sample.device ) elif torch.is_tensor(snake_case ) and len(timesteps.shape ) == 0: SCREAMING_SNAKE_CASE =timesteps[None].to(sample.device ) SCREAMING_SNAKE_CASE =self.time_proj(snake_case ) if self.config.use_timestep_embedding: SCREAMING_SNAKE_CASE =self.time_mlp(snake_case ) else: SCREAMING_SNAKE_CASE =timestep_embed[..., None] SCREAMING_SNAKE_CASE =timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) SCREAMING_SNAKE_CASE =timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down SCREAMING_SNAKE_CASE =() for downsample_block in self.down_blocks: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =downsample_block(hidden_states=snake_case ,temb=snake_case ) down_block_res_samples += res_samples # 3. mid if self.mid_block: SCREAMING_SNAKE_CASE =self.mid_block(snake_case ,snake_case ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): SCREAMING_SNAKE_CASE =down_block_res_samples[-1:] SCREAMING_SNAKE_CASE =down_block_res_samples[:-1] SCREAMING_SNAKE_CASE =upsample_block(snake_case ,res_hidden_states_tuple=snake_case ,temb=snake_case ) # 5. post-process if self.out_block: SCREAMING_SNAKE_CASE =self.out_block(snake_case ,snake_case ) if not return_dict: return (sample,) return UNetaDOutput(sample=snake_case )
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence SCREAMING_SNAKE_CASE =gray_code_sequence_string(lowerCAmelCase_ ) # # convert them to integers for i in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =int(sequence[i], 2 ) return sequence def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] SCREAMING_SNAKE_CASE =1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits SCREAMING_SNAKE_CASE =gray_code_sequence_string(bit_count - 1 ) SCREAMING_SNAKE_CASE =[] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): SCREAMING_SNAKE_CASE ='0' + smaller_sequence[i] sequence.append(lowerCAmelCase_ ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): SCREAMING_SNAKE_CASE ='1' + smaller_sequence[i] sequence.append(lowerCAmelCase_ ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =SwinConfig(image_size=192 ) if "base" in model_name: SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =128 SCREAMING_SNAKE_CASE =(2, 2, 18, 2) SCREAMING_SNAKE_CASE =(4, 8, 16, 32) elif "large" in model_name: SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =192 SCREAMING_SNAKE_CASE =(2, 2, 18, 2) SCREAMING_SNAKE_CASE =(6, 12, 24, 48) else: raise ValueError('Model not supported, only supports base and large variants' ) SCREAMING_SNAKE_CASE =window_size SCREAMING_SNAKE_CASE =embed_dim SCREAMING_SNAKE_CASE =depths SCREAMING_SNAKE_CASE =num_heads return config def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if "encoder.mask_token" in name: SCREAMING_SNAKE_CASE =name.replace('encoder.mask_token', 'embeddings.mask_token' ) if "encoder.patch_embed.proj" in name: SCREAMING_SNAKE_CASE =name.replace('encoder.patch_embed.proj', 'embeddings.patch_embeddings.projection' ) if "encoder.patch_embed.norm" in name: SCREAMING_SNAKE_CASE =name.replace('encoder.patch_embed.norm', 'embeddings.norm' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE =name.replace('attn.proj', 'attention.output.dense' ) if "attn" in name: SCREAMING_SNAKE_CASE =name.replace('attn', 'attention.self' ) if "norm1" in name: SCREAMING_SNAKE_CASE =name.replace('norm1', 'layernorm_before' ) if "norm2" in name: SCREAMING_SNAKE_CASE =name.replace('norm2', 'layernorm_after' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE =name.replace('mlp.fc1', 'intermediate.dense' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE =name.replace('mlp.fc2', 'output.dense' ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE ='layernorm.weight' if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE ='layernorm.bias' if "decoder" in name: pass else: SCREAMING_SNAKE_CASE ='swin.' + name return name def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE =orig_state_dict.pop(lowerCAmelCase_ ) if "attn_mask" in key: pass elif "qkv" in key: SCREAMING_SNAKE_CASE =key.split('.' ) SCREAMING_SNAKE_CASE =int(key_split[2] ) SCREAMING_SNAKE_CASE =int(key_split[4] ) SCREAMING_SNAKE_CASE =model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE =val[:dim, :] SCREAMING_SNAKE_CASE =val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE =val[-dim:, :] else: SCREAMING_SNAKE_CASE =val[ :dim ] SCREAMING_SNAKE_CASE =val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE =val[ -dim: ] else: SCREAMING_SNAKE_CASE =val return orig_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' )['model'] SCREAMING_SNAKE_CASE =get_swin_config(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =SwinForMaskedImageModeling(lowerCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE =convert_state_dict(lowerCAmelCase_, lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ='http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE =ViTImageProcessor(size={'height': 192, 'width': 192} ) SCREAMING_SNAKE_CASE =Image.open(requests.get(lowerCAmelCase_, stream=lowerCAmelCase_ ).raw ) SCREAMING_SNAKE_CASE =image_processor(images=lowerCAmelCase_, return_tensors='pt' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ).logits print(outputs.keys() ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCAmelCase_ ) if push_to_hub: print(F'Pushing model and image processor for {model_name} to hub' ) model.push_to_hub(F'microsoft/{model_name}' ) image_processor.push_to_hub(F'microsoft/{model_name}' ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="swin-base-simmim-window6-192", type=str, choices=["swin-base-simmim-window6-192", "swin-large-simmim-window12-192"], help="Name of the Swin SimMIM model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth", type=str, help="Path to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) _lowerCamelCase =parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
334
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 a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =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 =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =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(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) 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 , SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) 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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, '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 snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =tempfile.mkdtemp() SCREAMING_SNAKE_CASE =5 # Realm tok SCREAMING_SNAKE_CASE =[ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'test', 'question', 'this', 'is', 'the', 'first', 'second', 'third', 'fourth', 'fifth', 'record', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname ,'realm_tokenizer' ) os.makedirs(snake_case ,exist_ok=snake_case ) SCREAMING_SNAKE_CASE =os.path.join(snake_case ,VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname ,'realm_block_records' ) os.makedirs(snake_case ,exist_ok=snake_case ) def _lowerCAmelCase ( self : str ): return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname ,'realm_tokenizer' ) ) def _lowerCAmelCase ( self : List[Any] ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =RealmConfig(num_block_records=self.num_block_records ) return config def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =Dataset.from_dict( { 'id': ['0', '1'], 'question': ['foo', 'bar'], 'answers': [['Foo', 'Bar'], ['Bar']], } ) return dataset def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =np.array( [ B'This is the first record', B'This is the second record', B'This is the third record', B'This is the fourth record', B'This is the fifth record', B'This is a longer longer longer record', ] ,dtype=snake_case ,) return block_records def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =RealmRetriever( block_records=self.get_dummy_block_records() ,tokenizer=self.get_tokenizer() ,) return retriever def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.get_config() SCREAMING_SNAKE_CASE =self.get_dummy_retriever() SCREAMING_SNAKE_CASE =retriever.tokenizer SCREAMING_SNAKE_CASE =np.array([0, 3] ,dtype='long' ) SCREAMING_SNAKE_CASE =tokenizer(['Test question'] ).input_ids SCREAMING_SNAKE_CASE =tokenizer( ['the fourth'] ,add_special_tokens=snake_case ,return_token_type_ids=snake_case ,return_attention_mask=snake_case ,).input_ids SCREAMING_SNAKE_CASE =config.reader_seq_len SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =retriever( snake_case ,snake_case ,answer_ids=snake_case ,max_length=snake_case ,return_tensors='np' ) self.assertEqual(len(snake_case ) ,2 ) self.assertEqual(len(snake_case ) ,2 ) self.assertEqual(len(snake_case ) ,2 ) self.assertEqual(concat_inputs.input_ids.shape ,(2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape ,(2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape ,(2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape ,(2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) ,['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]'] ,) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) ,['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]'] ,) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.get_config() SCREAMING_SNAKE_CASE =self.get_dummy_retriever() SCREAMING_SNAKE_CASE =retriever.tokenizer SCREAMING_SNAKE_CASE =np.array([0, 3, 5] ,dtype='long' ) SCREAMING_SNAKE_CASE =tokenizer(['Test question'] ).input_ids SCREAMING_SNAKE_CASE =tokenizer( ['the fourth', 'longer longer'] ,add_special_tokens=snake_case ,return_token_type_ids=snake_case ,return_attention_mask=snake_case ,).input_ids SCREAMING_SNAKE_CASE =config.reader_seq_len SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =retriever( snake_case ,snake_case ,answer_ids=snake_case ,max_length=snake_case ,return_tensors='np' ) self.assertEqual([False, True, True] ,snake_case ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] ,snake_case ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] ,snake_case ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname ,'realm_block_records' ) ) # Test local path SCREAMING_SNAKE_CASE =retriever.from_pretrained(os.path.join(self.tmpdirname ,'realm_block_records' ) ) self.assertEqual(retriever.block_records[0] ,B'This is the first record' ) # Test mocked remote path with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download: SCREAMING_SNAKE_CASE =os.path.join( os.path.join(self.tmpdirname ,'realm_block_records' ) ,_REALM_BLOCK_RECORDS_FILENAME ) SCREAMING_SNAKE_CASE =RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' ) self.assertEqual(retriever.block_records[0] ,B'This is the first record' )
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase =data_utils.TransfoXLTokenizer _lowerCamelCase =data_utils.TransfoXLCorpus _lowerCamelCase =data_utils _lowerCamelCase =data_utils def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(lowerCAmelCase_, 'rb' ) as fp: SCREAMING_SNAKE_CASE =pickle.load(lowerCAmelCase_, encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE =pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'Save vocabulary to {pytorch_vocab_dump_path}' ) SCREAMING_SNAKE_CASE =corpus.vocab.__dict__ torch.save(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =corpus.__dict__ corpus_dict_no_vocab.pop('vocab', lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'Save dataset to {pytorch_dataset_dump_path}' ) torch.save(lowerCAmelCase_, lowerCAmelCase_ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE =os.path.abspath(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =os.path.abspath(lowerCAmelCase_ ) print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE =TransfoXLConfig() else: SCREAMING_SNAKE_CASE =TransfoXLConfig.from_json_file(lowerCAmelCase_ ) print(F'Building PyTorch model from configuration: {config}' ) SCREAMING_SNAKE_CASE =TransfoXLLMHeadModel(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =load_tf_weights_in_transfo_xl(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Save pytorch-model SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, lowerCAmelCase_ ) print(F'Save PyTorch model to {os.path.abspath(lowerCAmelCase_ )}' ) torch.save(model.state_dict(), lowerCAmelCase_ ) print(F'Save configuration file to {os.path.abspath(lowerCAmelCase_ )}' ) with open(lowerCAmelCase_, 'w', encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) _lowerCamelCase =parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
import math import sys def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if number != int(lowerCAmelCase_ ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 SCREAMING_SNAKE_CASE =[-1] * (number + 1) SCREAMING_SNAKE_CASE =0 for i in range(1, number + 1 ): SCREAMING_SNAKE_CASE =sys.maxsize SCREAMING_SNAKE_CASE =int(math.sqrt(lowerCAmelCase_ ) ) for j in range(1, root + 1 ): SCREAMING_SNAKE_CASE =1 + answers[i - (j**2)] SCREAMING_SNAKE_CASE =min(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import requests _lowerCamelCase ="https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'], 1 ): print(F'{i}.) {article["title"]}' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Tuple ,snake_case : Dict ,snake_case : Union[str, Any]=7 ,snake_case : List[Any]=3 ,snake_case : Tuple=18 ,snake_case : int=30 ,snake_case : Optional[int]=400 ,snake_case : Tuple=True ,snake_case : Optional[int]=None ,snake_case : Optional[int]=True ,): SCREAMING_SNAKE_CASE =size if size is not None else {'height': 18, 'width': 18} SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =min_resolution SCREAMING_SNAKE_CASE =max_resolution SCREAMING_SNAKE_CASE =do_resize SCREAMING_SNAKE_CASE =size SCREAMING_SNAKE_CASE =apply_ocr def _lowerCAmelCase ( self : str ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =LayoutLMvaImageProcessingTester(self ) @property def _lowerCAmelCase ( self : int ): return self.image_processor_tester.prepare_image_processor_dict() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case ,'do_resize' ) ) self.assertTrue(hasattr(snake_case ,'size' ) ) self.assertTrue(hasattr(snake_case ,'apply_ocr' ) ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'height': 18, 'width': 18} ) SCREAMING_SNAKE_CASE =self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ) self.assertEqual(image_processor.size ,{'height': 42, 'width': 42} ) def _lowerCAmelCase ( self : Tuple ): pass def _lowerCAmelCase ( self : List[Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) ,) self.assertIsInstance(encoding.words ,snake_case ) self.assertIsInstance(encoding.boxes ,snake_case ) # Test batched SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) ,) def _lowerCAmelCase ( self : Union[str, Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,numpify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) ,) # Test batched SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) ,) def _lowerCAmelCase ( self : Tuple ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) ,) # Test batched SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) ,) def _lowerCAmelCase ( self : Dict ): # with apply_OCR = True SCREAMING_SNAKE_CASE =LayoutLMvaImageProcessor() from datasets import load_dataset SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_docvqa' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ).convert('RGB' ) SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape ,(1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) ,len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 SCREAMING_SNAKE_CASE =[['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 SCREAMING_SNAKE_CASE =[[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words ,snake_case ) self.assertListEqual(encoding.boxes ,snake_case ) # with apply_OCR = False SCREAMING_SNAKE_CASE =LayoutLMvaImageProcessor(apply_ocr=snake_case ) SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape ,(1, 3, 224, 224) )
334
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_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =seq_length SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_input_mask SCREAMING_SNAKE_CASE =use_token_type_ids SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_choices SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Optional[int] ): 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 _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=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 _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Dict ): for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(snake_case ): SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) self.assertIsInstance(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =FlaxAutoModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) self.assertIsInstance(snake_case ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): for model_name in ["roberta-base", "roberta-large"]: with self.subTest(snake_case ): SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) self.assertIsInstance(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =FlaxAutoModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) self.assertIsInstance(snake_case ,snake_case ) @slow def _lowerCAmelCase ( self : int ): for model_name in ["bert-base-cased", "bert-large-uncased"]: SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(snake_case ) SCREAMING_SNAKE_CASE =FlaxBertModel.from_pretrained(snake_case ) SCREAMING_SNAKE_CASE =tokenizer('Do you support jax jitted function?' ,return_tensors=TensorType.JAX ) @jax.jit def eval(**snake_case : List[str] ): return model(**snake_case ) eval(**snake_case ).block_until_ready() @slow def _lowerCAmelCase ( self : Optional[Any] ): for model_name in ["roberta-base", "roberta-large"]: SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(snake_case ) SCREAMING_SNAKE_CASE =FlaxRobertaModel.from_pretrained(snake_case ) SCREAMING_SNAKE_CASE =tokenizer('Do you support jax jitted function?' ,return_tensors=TensorType.JAX ) @jax.jit def eval(**snake_case : Tuple ): return model(**snake_case ) eval(**snake_case ).block_until_ready() def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaisesRegex( snake_case ,'bert-base is not a local folder and is not a valid model identifier' ): SCREAMING_SNAKE_CASE =FlaxAutoModel.from_pretrained('bert-base' ) def _lowerCAmelCase ( self : str ): with self.assertRaisesRegex( snake_case ,r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): SCREAMING_SNAKE_CASE =FlaxAutoModel.from_pretrained(snake_case ,revision='aaaaaa' ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaisesRegex( snake_case ,'hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack' ,): SCREAMING_SNAKE_CASE =FlaxAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def _lowerCAmelCase ( self : Tuple ): with self.assertRaisesRegex(snake_case ,'Use `from_pt=True` to load this model' ): SCREAMING_SNAKE_CASE =FlaxAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _lowerCamelCase =logging.get_logger(__name__) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =to_pil_image(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =pil_image.size SCREAMING_SNAKE_CASE =pytesseract.image_to_data(lowerCAmelCase_, lang=lowerCAmelCase_, output_type='dict', config=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE =[idx for idx, word in enumerate(lowerCAmelCase_ ) if not word.strip()] SCREAMING_SNAKE_CASE =[word for idx, word in enumerate(lowerCAmelCase_ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE =[coord for idx, coord in enumerate(lowerCAmelCase_ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE =[coord for idx, coord in enumerate(lowerCAmelCase_ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE =[coord for idx, coord in enumerate(lowerCAmelCase_ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE =[coord for idx, coord in enumerate(lowerCAmelCase_ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE =[] for x, y, w, h in zip(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =[x, y, x + w, y + h] actual_boxes.append(lowerCAmelCase_ ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE =[] for box in actual_boxes: normalized_boxes.append(normalize_box(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) ) assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = ['pixel_values'] def __init__( self : int ,snake_case : bool = True ,snake_case : Dict[str, int] = None ,snake_case : PILImageResampling = PILImageResampling.BILINEAR ,snake_case : bool = True ,snake_case : float = 1 / 255 ,snake_case : bool = True ,snake_case : Union[float, Iterable[float]] = None ,snake_case : Union[float, Iterable[float]] = None ,snake_case : bool = True ,snake_case : Optional[str] = None ,snake_case : Optional[str] = "" ,**snake_case : Any ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =size if size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE =get_size_dict(snake_case ) SCREAMING_SNAKE_CASE =do_resize SCREAMING_SNAKE_CASE =size SCREAMING_SNAKE_CASE =resample SCREAMING_SNAKE_CASE =do_rescale SCREAMING_SNAKE_CASE =rescale_value SCREAMING_SNAKE_CASE =do_normalize SCREAMING_SNAKE_CASE =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE =image_std if image_std is not None else IMAGENET_STANDARD_STD SCREAMING_SNAKE_CASE =apply_ocr SCREAMING_SNAKE_CASE =ocr_lang SCREAMING_SNAKE_CASE =tesseract_config def _lowerCAmelCase ( self : Optional[int] ,snake_case : np.ndarray ,snake_case : Dict[str, int] ,snake_case : PILImageResampling = PILImageResampling.BILINEAR ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : Union[str, Any] ,): SCREAMING_SNAKE_CASE =get_size_dict(snake_case ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) SCREAMING_SNAKE_CASE =(size['height'], size['width']) return resize(snake_case ,size=snake_case ,resample=snake_case ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : Tuple ,snake_case : np.ndarray ,snake_case : Union[int, float] ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : Optional[int] ,): return rescale(snake_case ,scale=snake_case ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : Any ,snake_case : np.ndarray ,snake_case : Union[float, Iterable[float]] ,snake_case : Union[float, Iterable[float]] ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : Union[str, Any] ,): return normalize(snake_case ,mean=snake_case ,std=snake_case ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : ImageInput ,snake_case : bool = None ,snake_case : Dict[str, int] = None ,snake_case : str=None ,snake_case : bool = None ,snake_case : float = None ,snake_case : bool = None ,snake_case : Union[float, Iterable[float]] = None ,snake_case : Union[float, Iterable[float]] = None ,snake_case : bool = None ,snake_case : Optional[str] = None ,snake_case : Optional[str] = None ,snake_case : Optional[Union[str, TensorType]] = None ,snake_case : ChannelDimension = ChannelDimension.FIRST ,**snake_case : Optional[Any] ,): SCREAMING_SNAKE_CASE =do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE =size if size is not None else self.size SCREAMING_SNAKE_CASE =get_size_dict(snake_case ) SCREAMING_SNAKE_CASE =resample if resample is not None else self.resample SCREAMING_SNAKE_CASE =do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE =rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE =do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE =image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE =image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE =apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE =ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE =tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE =make_list_of_images(snake_case ) if not valid_images(snake_case ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('If do_normalize is True, image_mean and image_std must be specified.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE =[to_numpy_array(snake_case ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self ,'pytesseract' ) SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[] for image in images: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =apply_tesseract(snake_case ,snake_case ,snake_case ) words_batch.append(snake_case ) boxes_batch.append(snake_case ) if do_resize: SCREAMING_SNAKE_CASE =[self.resize(image=snake_case ,size=snake_case ,resample=snake_case ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE =[self.rescale(image=snake_case ,scale=snake_case ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE =[self.normalize(image=snake_case ,mean=snake_case ,std=snake_case ) for image in images] SCREAMING_SNAKE_CASE =[to_channel_dimension_format(snake_case ,snake_case ) for image in images] SCREAMING_SNAKE_CASE =BatchFeature(data={'pixel_values': images} ,tensor_type=snake_case ) if apply_ocr: SCREAMING_SNAKE_CASE =words_batch SCREAMING_SNAKE_CASE =boxes_batch return data
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =TapasConfig.from_json_file(lowerCAmelCase_ ) # set absolute/relative position embeddings parameter SCREAMING_SNAKE_CASE =reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": SCREAMING_SNAKE_CASE =TapasForQuestionAnswering(config=lowerCAmelCase_ ) elif task == "WTQ": # run_task_main.py hparams SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =True # hparam_utils.py hparams SCREAMING_SNAKE_CASE =0.66_4694 SCREAMING_SNAKE_CASE =0.20_7951 SCREAMING_SNAKE_CASE =0.12_1194 SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =0.035_2513 SCREAMING_SNAKE_CASE =TapasForQuestionAnswering(config=lowerCAmelCase_ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =False # hparam_utils.py hparams SCREAMING_SNAKE_CASE =36.4519 SCREAMING_SNAKE_CASE =0.90_3421 SCREAMING_SNAKE_CASE =222.088 SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =0.76_3141 SCREAMING_SNAKE_CASE =TapasForQuestionAnswering(config=lowerCAmelCase_ ) elif task == "TABFACT": SCREAMING_SNAKE_CASE =TapasForSequenceClassification(config=lowerCAmelCase_ ) elif task == "MLM": SCREAMING_SNAKE_CASE =TapasForMaskedLM(config=lowerCAmelCase_ ) elif task == "INTERMEDIATE_PRETRAINING": SCREAMING_SNAKE_CASE =TapasModel(config=lowerCAmelCase_ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase_ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) SCREAMING_SNAKE_CASE =TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt', model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase_ ) print('Used relative position embeddings:', model.config.reset_position_index_per_cell ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--task", default="SQA", type=str, help="Model task for which to convert a checkpoint. Defaults to SQA." ) parser.add_argument( "--reset_position_index_per_cell", default=False, action="store_true", help="Whether to use relative position embeddings or not. Defaults to True.", ) parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--tapas_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained TAPAS model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _lowerCamelCase =parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = 0, lowerCAmelCase_ = 0 ): """simple docstring""" SCREAMING_SNAKE_CASE =right or len(lowerCAmelCase_ ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(lowerCAmelCase_, lowerCAmelCase_, left + 1, right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = ['image_processor', 'tokenizer'] __UpperCAmelCase = 'CLIPImageProcessor' __UpperCAmelCase = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : Any ,snake_case : Tuple=None ,snake_case : Optional[Any]=None ,**snake_case : str ): SCREAMING_SNAKE_CASE =None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,snake_case ,) SCREAMING_SNAKE_CASE =kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(snake_case ,snake_case ) def __call__( self : int ,snake_case : Tuple=None ,snake_case : Optional[Any]=None ,snake_case : Union[str, Any]=None ,**snake_case : Optional[int] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE =self.tokenizer(snake_case ,return_tensors=snake_case ,**snake_case ) if images is not None: SCREAMING_SNAKE_CASE =self.image_processor(snake_case ,return_tensors=snake_case ,**snake_case ) if text is not None and images is not None: SCREAMING_SNAKE_CASE =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**snake_case ) ,tensor_type=snake_case ) def _lowerCAmelCase ( self : str ,*snake_case : List[Any] ,**snake_case : str ): return self.tokenizer.batch_decode(*snake_case ,**snake_case ) def _lowerCAmelCase ( self : Optional[Any] ,*snake_case : Dict ,**snake_case : Tuple ): return self.tokenizer.decode(*snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.tokenizer.model_input_names SCREAMING_SNAKE_CASE =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _lowerCAmelCase ( self : Any ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,snake_case ,) return self.image_processor_class @property def _lowerCAmelCase ( self : Dict ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,snake_case ,) return self.image_processor
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return [tuple(lowerCAmelCase_ )] SCREAMING_SNAKE_CASE =[] def generate(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =[0] * n res.append(tuple(lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =0 while i < n: if c[i] < i: if i % 2 == 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =arr[i], arr[0] else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =arr[i], arr[c[i]] res.append(tuple(lowerCAmelCase_ ) ) c[i] += 1 SCREAMING_SNAKE_CASE =0 else: SCREAMING_SNAKE_CASE =0 i += 1 generate(len(lowerCAmelCase_ ), lowerCAmelCase_ ) return res if __name__ == "__main__": _lowerCamelCase =input("Enter numbers separated by a comma:\n").strip() _lowerCamelCase =[int(item) for item in user_input.split(",")] print(heaps(arr))
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[0] * len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[1] * len(lowerCAmelCase_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCAmelCase_ ) ): if indegree[i] == 0: queue.append(lowerCAmelCase_ ) while queue: SCREAMING_SNAKE_CASE =queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: SCREAMING_SNAKE_CASE =long_dist[vertex] + 1 if indegree[x] == 0: queue.append(lowerCAmelCase_ ) print(max(lowerCAmelCase_ ) ) # Adjacency list of Graph _lowerCamelCase ={0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
import logging import os from .state import PartialState class a_ ( logging.LoggerAdapter ): """simple docstring""" @staticmethod def _lowerCAmelCase ( snake_case : Dict ): SCREAMING_SNAKE_CASE =PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _lowerCAmelCase ( self : int ,snake_case : Dict ,snake_case : int ,*snake_case : str ,**snake_case : List[str] ): if PartialState._shared_state == {}: raise RuntimeError( 'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' ) SCREAMING_SNAKE_CASE =kwargs.pop('main_process_only' ,snake_case ) SCREAMING_SNAKE_CASE =kwargs.pop('in_order' ,snake_case ) if self.isEnabledFor(snake_case ): if self._should_log(snake_case ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.process(snake_case ,snake_case ) self.logger.log(snake_case ,snake_case ,*snake_case ,**snake_case ) elif in_order: SCREAMING_SNAKE_CASE =PartialState() for i in range(state.num_processes ): if i == state.process_index: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.process(snake_case ,snake_case ) self.logger.log(snake_case ,snake_case ,*snake_case ,**snake_case ) state.wait_for_everyone() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None ): """simple docstring""" if log_level is None: SCREAMING_SNAKE_CASE =os.environ.get('ACCELERATE_LOG_LEVEL', lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =logging.getLogger(lowerCAmelCase_ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(lowerCAmelCase_, {} )
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,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 ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =config_and_inputs SCREAMING_SNAKE_CASE ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) SCREAMING_SNAKE_CASE =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE =['pixel_values'] self.assertListEqual(arg_names[:1] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) _lowerCamelCase =models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation="relu") ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation="relu")) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=1_28, activation="relu")) classifier.add(layers.Dense(units=1, activation="sigmoid")) # Compiling the CNN classifier.compile( optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') _lowerCamelCase =tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 2_55, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) _lowerCamelCase =tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 2_55) _lowerCamelCase =train_datagen.flow_from_directory( "dataset/training_set", target_size=(64, 64), batch_size=32, class_mode="binary" ) _lowerCamelCase =test_datagen.flow_from_directory( "dataset/test_set", target_size=(64, 64), batch_size=32, class_mode="binary" ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save("cnn.h5") # Part 3 - Making new predictions _lowerCamelCase =tf.keras.preprocessing.image.load_img( "dataset/single_prediction/image.png", target_size=(64, 64) ) _lowerCamelCase =tf.keras.preprocessing.image.img_to_array(test_image) _lowerCamelCase =np.expand_dims(test_image, axis=0) _lowerCamelCase =classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: _lowerCamelCase ="Normal" if result[0][0] == 1: _lowerCamelCase ="Abnormality detected"
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
from dataclasses import dataclass, field from typing import Optional @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be trained.'} ) __UpperCAmelCase = field( default='./' , metadata={'help': 'Save dir where model repo is cloned and models updates are saved to.'} ) __UpperCAmelCase = field( default='codeparrot/codeparrot-clean-train' , metadata={'help': 'Name or path of training dataset.'} ) __UpperCAmelCase = field( default='codeparrot/codeparrot-clean-valid' , metadata={'help': 'Name or path of validation dataset.'} ) __UpperCAmelCase = field(default=2 , metadata={'help': 'Batch size for training.'} ) __UpperCAmelCase = field(default=2 , metadata={'help': 'Batch size for evaluation.'} ) __UpperCAmelCase = field(default=0.1 , metadata={'help': 'Value of weight decay.'} ) __UpperCAmelCase = field( default=10_000 , metadata={'help': 'Size of buffer used to shuffle streaming dataset.'} ) __UpperCAmelCase = field(default=2e-4 , metadata={'help': 'Learning rate fo training.'} ) __UpperCAmelCase = field(default='cosine' , metadata={'help': 'Learning rate.'} ) __UpperCAmelCase = field( default=750 , metadata={'help': 'Number of warmup steps in the learning rate schedule.'} ) __UpperCAmelCase = field( default=16 , metadata={'help': 'Number of gradient accumulation steps.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Use gradient checkpointing to reduce memory footprint.'} ) __UpperCAmelCase = field(default=50_000 , metadata={'help': 'Maximum number of training steps.'} ) __UpperCAmelCase = field( default=-1 , metadata={'help': 'Maximum number of evaluation steps. If -1 the full dataset is evaluated.'} ) __UpperCAmelCase = field(default=1_024 , metadata={'help': 'Sequence lengths used for training.'} ) __UpperCAmelCase = field(default=1 , metadata={'help': 'Training seed.'} ) __UpperCAmelCase = field( default=1_024 , metadata={'help': 'Interval to save checkpoints. Measured as number of forward passes not training steps.'} , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'States path if the training should continue from a checkpoint folder.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'If True the data is pretokenized.'} ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be evaluated.'} ) __UpperCAmelCase = field( default='codeparrot/codeparrot-clean-valid' , metadata={'help': 'Name or path of validation dataset.'} ) __UpperCAmelCase = field(default=2 , metadata={'help': 'Batch size used for evaluation.'} ) __UpperCAmelCase = field( default=-1 , metadata={'help': 'Maximum number of evaluation steps. If -1 the full dataset is evaluated.'} ) __UpperCAmelCase = field(default=1_024 , metadata={'help': 'Length of sequences to be evaluated.'} ) __UpperCAmelCase = field(default=1 , metadata={'help': 'Random seed used for evaluation.'} ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='codeparrot/codeparrot' , metadata={'help': 'Model name or path of model to be evaluated.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Number of workers used for code evaluation.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'The number of human-eval tasks to run. If not included all tasks are evaluated.'} , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Sample from the language model\'s output distribution.'} ) __UpperCAmelCase = field(default=0.2 , metadata={'help': 'Sampling temperature used for generation.'} ) __UpperCAmelCase = field(default=256 , metadata={'help': 'Maximum number of newly generated tokens.'} ) __UpperCAmelCase = field(default=0 , metadata={'help': 'Top-k parameter used for generation.'} ) __UpperCAmelCase = field(default=0.95 , metadata={'help': 'Top-p parameter used for nucleus sampling.'} ) __UpperCAmelCase = field(default=10 , metadata={'help': 'Number of generations to run in parallel.'} ) __UpperCAmelCase = field( default=200 , metadata={'help': 'Number of completions to generate for each sample.'} ) __UpperCAmelCase = field(default=1 , metadata={'help': 'Random seed used for evaluation.'} ) __UpperCAmelCase = field( default='eval_results.json' , metadata={'help': 'Random seed used for evaluation.'} ) __UpperCAmelCase = field( default='0' , metadata={'help': 'Allow `code_eval` to execute Python code on machine'} ) __UpperCAmelCase = field( default=-1 , metadata={ 'help': ( 'Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive' ' number corresponds to which GPU device id to run on.' ) } , ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={ 'help': 'The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.' } , ) __UpperCAmelCase = field( default='transformersbook/codeparrot' , metadata={'help': 'Folder or name of dataset to process.'} ) __UpperCAmelCase = field( default='codeparrot-clean' , metadata={'help': 'Folder to save processed processed dataset.'} ) __UpperCAmelCase = field( default=100_000 , metadata={'help': 'Number of files to save per JSON output file.'} ) __UpperCAmelCase = field(default='content' , metadata={'help': 'Column containing text data to process.'} ) __UpperCAmelCase = field( default=1_000 , metadata={'help': 'Maximum line length in file, otherwise file is filtered.'} ) __UpperCAmelCase = field( default=100 , metadata={'help': 'Maximum mean line length in file, otherwise file is filtered.'} ) __UpperCAmelCase = field( default=0.25 , metadata={'help': 'Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'} ) __UpperCAmelCase = field( default=1.5 , metadata={'help': 'Minimum character token ratio for the file, otherwise file is filtered.'} ) __UpperCAmelCase = field( default=0.7 , metadata={'help': 'Probability for filtering config, test and uncommon files.'} ) __UpperCAmelCase = field( default='codeparrot/codeparrot' , metadata={'help': 'Name or path to the tokenizer.'} , ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'If True, near-duplicate samples are removed.'} ) __UpperCAmelCase = field( default=0.85 , metadata={'help': 'Jaccard threshold for near-duplicate samples.'} ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='gpt2' , metadata={'help': 'Base tokenizer to build new tokenizer from.'} ) __UpperCAmelCase = field( default='transformersbook/codeparrot-train' , metadata={'help': 'Dataset to train tokenizer on.'} ) __UpperCAmelCase = field(default='content' , metadata={'help': 'Column containing text data to process.'} ) __UpperCAmelCase = field(default=200_000 , metadata={'help': 'Number of examples to train tokenizer on.'} ) __UpperCAmelCase = field( default=32_768 , metadata={'help': 'Number of examples to train the tokenizer on.'} ) __UpperCAmelCase = field(default='codeparrot' , metadata={'help': 'Name of new tokenizer.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Push saved tokenizer to the hub.'} ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='codeparrot/codeparrot' , metadata={'help': 'Name or path to the tokenizer.'} ) __UpperCAmelCase = field( default='codeparrot/codeparrot-clean-train' , metadata={'help': 'Name or path to the dataset to pretokenize.'} ) __UpperCAmelCase = field( default='tokenized-codeparrot-train' , metadata={'help': 'Repo name of the pretokenized data.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Number of workers used for code evaluation.'} ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = field( default='gpt2-large' , metadata={'help': 'Configuration to use for model initialization.'} ) __UpperCAmelCase = field( default='codeparrot/codeparrot' , metadata={'help': 'Tokenizer attached to model.'} ) __UpperCAmelCase = field(default='codeparrot' , metadata={'help': 'Name of the created model.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Push saved tokenizer to the hub.'} )
334
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE =load_dataset('glue', 'mrpc' ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowerCAmelCase_, max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE =datasets.map( lowerCAmelCase_, batched=lowerCAmelCase_, remove_columns=['idx', 'sentence1', 'sentence2'], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE =16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE =8 else: SCREAMING_SNAKE_CASE =None return tokenizer.pad( lowerCAmelCase_, padding='longest', max_length=lowerCAmelCase_, pad_to_multiple_of=lowerCAmelCase_, return_tensors='pt', ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['train'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['validation'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if os.environ.get('TESTING_MOCKED_DATALOADERS', lowerCAmelCase_ ) == "1": SCREAMING_SNAKE_CASE =2 # Initialize accelerator SCREAMING_SNAKE_CASE =Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE =config['lr'] SCREAMING_SNAKE_CASE =int(config['num_epochs'] ) SCREAMING_SNAKE_CASE =int(config['seed'] ) SCREAMING_SNAKE_CASE =int(config['batch_size'] ) SCREAMING_SNAKE_CASE =evaluate.load('glue', 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE =AutoModelForSequenceClassification.from_pretrained('bert-base-cased', return_dict=lowerCAmelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE =model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE =AdamW(params=model.parameters(), lr=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =get_dataloaders(lowerCAmelCase_, lowerCAmelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE =get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_, num_warmup_steps=100, num_training_steps=(len(lowerCAmelCase_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.prepare( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCAmelCase_, references=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:', lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision', type=lowerCAmelCase_, default=lowerCAmelCase_, choices=['no', 'fp16', 'bf16', 'fp8'], help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.', ) parser.add_argument('--cpu', action='store_true', help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE ={'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCAmelCase_, lowerCAmelCase_ ) if __name__ == "__main__": main()
334
1
import numpy as np import datasets _lowerCamelCase ="\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n" _lowerCamelCase ="\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n" _lowerCamelCase ="\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {'mahalanobis': array([0.5])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : List[str] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'X': datasets.Sequence(datasets.Value('float' ,id='sequence' ) ,id='X' ), } ) ,) def _lowerCAmelCase ( self : List[str] ,snake_case : Optional[Any] ,snake_case : List[Any] ): # convert to numpy arrays SCREAMING_SNAKE_CASE =np.array(snake_case ) SCREAMING_SNAKE_CASE =np.array(snake_case ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('Expected `X` to be a 2D vector' ) if len(reference_distribution.shape ) != 2: raise ValueError('Expected `reference_distribution` to be a 2D vector' ) if reference_distribution.shape[0] < 2: raise ValueError( 'Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension' ) # Get mahalanobis distance for each prediction SCREAMING_SNAKE_CASE =X - np.mean(snake_case ) SCREAMING_SNAKE_CASE =np.cov(reference_distribution.T ) try: SCREAMING_SNAKE_CASE =np.linalg.inv(snake_case ) except np.linalg.LinAlgError: SCREAMING_SNAKE_CASE =np.linalg.pinv(snake_case ) SCREAMING_SNAKE_CASE =np.dot(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =np.dot(snake_case ,X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase ="\\n Text data.\n Second line of data." _lowerCamelCase ="file" @pytest.fixture(scope='session' ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / (FILE_PATH + '.zstd') SCREAMING_SNAKE_CASE =bytes(lowerCAmelCase_, 'utf-8' ) with zstd.open(lowerCAmelCase_, 'wb' ) as f: f.write(lowerCAmelCase_ ) return path @pytest.fixture def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(os.path.join(tmpfs.local_root_dir, lowerCAmelCase_ ), 'w' ) as f: f.write(lowerCAmelCase_ ) return FILE_PATH @pytest.mark.parametrize('compression_format', ['gzip', 'xz', 'zstd'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ={'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path} SCREAMING_SNAKE_CASE =input_paths[compression_format] SCREAMING_SNAKE_CASE =tmp_path / 'cache' SCREAMING_SNAKE_CASE =DownloadConfig(cache_dir=lowerCAmelCase_, extract_compressed_file=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =cached_path(lowerCAmelCase_, download_config=lowerCAmelCase_ ) with open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read() with open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize('default_extracted', [True, False] ) @pytest.mark.parametrize('default_cache_dir', [True, False] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='custom_cache' SCREAMING_SNAKE_CASE ='custom_extracted_dir' SCREAMING_SNAKE_CASE =tmp_path / 'custom_extracted_path' if default_extracted: SCREAMING_SNAKE_CASE =('downloads' if default_cache_dir else custom_cache_dir, 'extracted') else: monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR', lowerCAmelCase_ ) monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH', str(lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE =xz_file SCREAMING_SNAKE_CASE =( DownloadConfig(extract_compressed_file=lowerCAmelCase_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir, extract_compressed_file=lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =cached_path(lowerCAmelCase_, download_config=lowerCAmelCase_ ) assert Path(lowerCAmelCase_ ).parent.parts[-2:] == expected def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(Path(lowerCAmelCase_ ).resolve() ) assert cached_path(lowerCAmelCase_ ) == text_file # relative path SCREAMING_SNAKE_CASE =str(Path(lowerCAmelCase_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(lowerCAmelCase_ ) == text_file def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path.resolve() / '__missing_file__.txt' ) with pytest.raises(lowerCAmelCase_ ): cached_path(lowerCAmelCase_ ) # relative path SCREAMING_SNAKE_CASE ='./__missing_file__.txt' with pytest.raises(lowerCAmelCase_ ): cached_path(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_from_cache(F'tmp://{tmpfs_file}' ) with open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read() assert output_file_content == FILE_CONTENT @patch('datasets.config.HF_DATASETS_OFFLINE', lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" with pytest.raises(lowerCAmelCase_ ): cached_path('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE', lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(lowerCAmelCase_ ): http_get('https://huggingface.co', temp_file=lowerCAmelCase_ ) with pytest.raises(lowerCAmelCase_ ): http_head('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE', lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(lowerCAmelCase_ ): ftp_get('ftp://huggingface.co', temp_file=lowerCAmelCase_ ) with pytest.raises(lowerCAmelCase_ ): ftp_head('ftp://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE', lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(lowerCAmelCase_ ): fsspec_get('s3://huggingface.co', temp_file=lowerCAmelCase_ ) with pytest.raises(lowerCAmelCase_ ): fsspec_head('s3://huggingface.co' )
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": SCREAMING_SNAKE_CASE =timm.create_model('levit_128s', pretrained=lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =timm.create_model('levit_128', pretrained=lowerCAmelCase_ ) if hidden_sizes == 192: SCREAMING_SNAKE_CASE =timm.create_model('levit_192', pretrained=lowerCAmelCase_ ) if hidden_sizes == 256: SCREAMING_SNAKE_CASE =timm.create_model('levit_256', pretrained=lowerCAmelCase_ ) if hidden_sizes == 384: SCREAMING_SNAKE_CASE =timm.create_model('levit_384', pretrained=lowerCAmelCase_ ) from_model.eval() SCREAMING_SNAKE_CASE =LevitForImageClassificationWithTeacher(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =from_model.state_dict() SCREAMING_SNAKE_CASE =list(from_model.state_dict().keys() ) SCREAMING_SNAKE_CASE =list(our_model.state_dict().keys() ) print(len(lowerCAmelCase_ ), len(lowerCAmelCase_ ) ) for i in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =weights[og_keys[i]] our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((2, 3, 224, 224) ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_ ).logits assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =name print(lowerCAmelCase_ ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) SCREAMING_SNAKE_CASE =LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'levit-128S': 128, 'levit-128': 128, 'levit-192': 192, 'levit-256': 256, 'levit-384': 384, } SCREAMING_SNAKE_CASE ={ 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384], num_attention_heads=[4, 6, 8], depths=[2, 3, 4], key_dim=[16, 16, 16], drop_path_rate=0, ), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384], num_attention_heads=[4, 8, 12], depths=[4, 4, 4], key_dim=[16, 16, 16], drop_path_rate=0, ), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384], num_attention_heads=[3, 5, 6], depths=[4, 4, 4], key_dim=[32, 32, 32], drop_path_rate=0, ), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512], num_attention_heads=[4, 6, 8], depths=[4, 4, 4], key_dim=[32, 32, 32], drop_path_rate=0, ), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768], num_attention_heads=[6, 9, 12], depths=[4, 4, 4], key_dim=[32, 32, 32], drop_path_rate=0.1, ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name], lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help="The name of the model you wish to convert, it must be one of the supported Levit* architecture,", ) parser.add_argument( "--pytorch_dump_folder_path", default="levit-dump-folder/", type=Path, required=False, help="Path to the output PyTorch model directory.", ) parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") parser.add_argument( "--no-push_to_hub", dest="push_to_hub", action="store_false", help="Do not push model and image processor to the hub", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() _lowerCamelCase =logging.get_logger("transformers.models.encodec") _lowerCamelCase ={ "quantizer.vq.layers.*._codebook.inited": "quantizer.layers.*.codebook.inited", "quantizer.vq.layers.*._codebook.cluster_size": "quantizer.layers.*.codebook.cluster_size", "quantizer.vq.layers.*._codebook.embed": "quantizer.layers.*.codebook.embed", "quantizer.vq.layers.*._codebook.embed_avg": "quantizer.layers.*.codebook.embed_avg", } _lowerCamelCase ={ "encoder.model.0.conv.conv": "encoder.layers.0.conv", "encoder.model.1.block.1.conv.conv": "encoder.layers.1.block.1.conv", "encoder.model.1.block.3.conv.conv": "encoder.layers.1.block.3.conv", "encoder.model.1.shortcut.conv.conv": "encoder.layers.1.shortcut.conv", "encoder.model.3.conv.conv": "encoder.layers.3.conv", "encoder.model.4.block.1.conv.conv": "encoder.layers.4.block.1.conv", "encoder.model.4.block.3.conv.conv": "encoder.layers.4.block.3.conv", "encoder.model.4.shortcut.conv.conv": "encoder.layers.4.shortcut.conv", "encoder.model.6.conv.conv": "encoder.layers.6.conv", "encoder.model.7.block.1.conv.conv": "encoder.layers.7.block.1.conv", "encoder.model.7.block.3.conv.conv": "encoder.layers.7.block.3.conv", "encoder.model.7.shortcut.conv.conv": "encoder.layers.7.shortcut.conv", "encoder.model.9.conv.conv": "encoder.layers.9.conv", "encoder.model.10.block.1.conv.conv": "encoder.layers.10.block.1.conv", "encoder.model.10.block.3.conv.conv": "encoder.layers.10.block.3.conv", "encoder.model.10.shortcut.conv.conv": "encoder.layers.10.shortcut.conv", "encoder.model.12.conv.conv": "encoder.layers.12.conv", "encoder.model.13.lstm": "encoder.layers.13.lstm", "encoder.model.15.conv.conv": "encoder.layers.15.conv", } _lowerCamelCase ={ "encoder.model.0.conv.norm": "encoder.layers.0.norm", "encoder.model.1.block.1.conv.norm": "encoder.layers.1.block.1.norm", "encoder.model.1.block.3.conv.norm": "encoder.layers.1.block.3.norm", "encoder.model.1.shortcut.conv.norm": "encoder.layers.1.shortcut.norm", "encoder.model.3.conv.norm": "encoder.layers.3.norm", "encoder.model.4.block.1.conv.norm": "encoder.layers.4.block.1.norm", "encoder.model.4.block.3.conv.norm": "encoder.layers.4.block.3.norm", "encoder.model.4.shortcut.conv.norm": "encoder.layers.4.shortcut.norm", "encoder.model.6.conv.norm": "encoder.layers.6.norm", "encoder.model.7.block.1.conv.norm": "encoder.layers.7.block.1.norm", "encoder.model.7.block.3.conv.norm": "encoder.layers.7.block.3.norm", "encoder.model.7.shortcut.conv.norm": "encoder.layers.7.shortcut.norm", "encoder.model.9.conv.norm": "encoder.layers.9.norm", "encoder.model.10.block.1.conv.norm": "encoder.layers.10.block.1.norm", "encoder.model.10.block.3.conv.norm": "encoder.layers.10.block.3.norm", "encoder.model.10.shortcut.conv.norm": "encoder.layers.10.shortcut.norm", "encoder.model.12.conv.norm": "encoder.layers.12.norm", "encoder.model.15.conv.norm": "encoder.layers.15.norm", } _lowerCamelCase ={ "decoder.model.0.conv.conv": "decoder.layers.0.conv", "decoder.model.1.lstm": "decoder.layers.1.lstm", "decoder.model.3.convtr.convtr": "decoder.layers.3.conv", "decoder.model.4.block.1.conv.conv": "decoder.layers.4.block.1.conv", "decoder.model.4.block.3.conv.conv": "decoder.layers.4.block.3.conv", "decoder.model.4.shortcut.conv.conv": "decoder.layers.4.shortcut.conv", "decoder.model.6.convtr.convtr": "decoder.layers.6.conv", "decoder.model.7.block.1.conv.conv": "decoder.layers.7.block.1.conv", "decoder.model.7.block.3.conv.conv": "decoder.layers.7.block.3.conv", "decoder.model.7.shortcut.conv.conv": "decoder.layers.7.shortcut.conv", "decoder.model.9.convtr.convtr": "decoder.layers.9.conv", "decoder.model.10.block.1.conv.conv": "decoder.layers.10.block.1.conv", "decoder.model.10.block.3.conv.conv": "decoder.layers.10.block.3.conv", "decoder.model.10.shortcut.conv.conv": "decoder.layers.10.shortcut.conv", "decoder.model.12.convtr.convtr": "decoder.layers.12.conv", "decoder.model.13.block.1.conv.conv": "decoder.layers.13.block.1.conv", "decoder.model.13.block.3.conv.conv": "decoder.layers.13.block.3.conv", "decoder.model.13.shortcut.conv.conv": "decoder.layers.13.shortcut.conv", "decoder.model.15.conv.conv": "decoder.layers.15.conv", } _lowerCamelCase ={ "decoder.model.0.conv.norm": "decoder.layers.0.norm", "decoder.model.3.convtr.norm": "decoder.layers.3.norm", "decoder.model.4.block.1.conv.norm": "decoder.layers.4.block.1.norm", "decoder.model.4.block.3.conv.norm": "decoder.layers.4.block.3.norm", "decoder.model.4.shortcut.conv.norm": "decoder.layers.4.shortcut.norm", "decoder.model.6.convtr.norm": "decoder.layers.6.norm", "decoder.model.7.block.1.conv.norm": "decoder.layers.7.block.1.norm", "decoder.model.7.block.3.conv.norm": "decoder.layers.7.block.3.norm", "decoder.model.7.shortcut.conv.norm": "decoder.layers.7.shortcut.norm", "decoder.model.9.convtr.norm": "decoder.layers.9.norm", "decoder.model.10.block.1.conv.norm": "decoder.layers.10.block.1.norm", "decoder.model.10.block.3.conv.norm": "decoder.layers.10.block.3.norm", "decoder.model.10.shortcut.conv.norm": "decoder.layers.10.shortcut.norm", "decoder.model.12.convtr.norm": "decoder.layers.12.norm", "decoder.model.13.block.1.conv.norm": "decoder.layers.13.block.1.norm", "decoder.model.13.block.3.conv.norm": "decoder.layers.13.block.3.norm", "decoder.model.13.shortcut.conv.norm": "decoder.layers.13.shortcut.norm", "decoder.model.15.conv.norm": "decoder.layers.15.norm", } _lowerCamelCase ={ **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } _lowerCamelCase ={ **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } _lowerCamelCase =[] _lowerCamelCase =[] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for attribute in key.split('.' ): SCREAMING_SNAKE_CASE =getattr(lowerCAmelCase_, lowerCAmelCase_ ) if weight_type is not None: SCREAMING_SNAKE_CASE =getattr(lowerCAmelCase_, lowerCAmelCase_ ).shape else: SCREAMING_SNAKE_CASE =hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": SCREAMING_SNAKE_CASE =value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE =value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE =value elif weight_type == "bias": SCREAMING_SNAKE_CASE =value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE =value elif weight_type == "running_var": SCREAMING_SNAKE_CASE =value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE =value elif weight_type == "weight_ih_l0": SCREAMING_SNAKE_CASE =value elif weight_type == "weight_hh_l0": SCREAMING_SNAKE_CASE =value elif weight_type == "bias_ih_l0": SCREAMING_SNAKE_CASE =value elif weight_type == "bias_hh_l0": SCREAMING_SNAKE_CASE =value elif weight_type == "weight_ih_l1": SCREAMING_SNAKE_CASE =value elif weight_type == "weight_hh_l1": SCREAMING_SNAKE_CASE =value elif weight_type == "bias_ih_l1": SCREAMING_SNAKE_CASE =value elif weight_type == "bias_hh_l1": SCREAMING_SNAKE_CASE =value else: SCREAMING_SNAKE_CASE =value logger.info(F'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] if model_name == "encodec_24khz" or "encodec_32khz": SCREAMING_SNAKE_CASE =MAPPING_24K elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE =MAPPING_48K else: raise ValueError(F'Unsupported model: {model_name}' ) for name, value in orig_dict.items(): if should_ignore(lowerCAmelCase_, lowerCAmelCase_ ): logger.info(F'{name} was ignored' ) continue SCREAMING_SNAKE_CASE =False for key, mapped_key in MAPPING.items(): if "*" in key: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =key.split('.*.' ) if prefix in name and suffix in name: SCREAMING_SNAKE_CASE =suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue SCREAMING_SNAKE_CASE =True if "*" in mapped_key: SCREAMING_SNAKE_CASE =name.split(lowerCAmelCase_ )[0].split('.' )[-2] SCREAMING_SNAKE_CASE =mapped_key.replace('*', lowerCAmelCase_ ) if "weight_g" in name: SCREAMING_SNAKE_CASE ='weight_g' elif "weight_v" in name: SCREAMING_SNAKE_CASE ='weight_v' elif "weight_ih_l0" in name: SCREAMING_SNAKE_CASE ='weight_ih_l0' elif "weight_hh_l0" in name: SCREAMING_SNAKE_CASE ='weight_hh_l0' elif "bias_ih_l0" in name: SCREAMING_SNAKE_CASE ='bias_ih_l0' elif "bias_hh_l0" in name: SCREAMING_SNAKE_CASE ='bias_hh_l0' elif "weight_ih_l1" in name: SCREAMING_SNAKE_CASE ='weight_ih_l1' elif "weight_hh_l1" in name: SCREAMING_SNAKE_CASE ='weight_hh_l1' elif "bias_ih_l1" in name: SCREAMING_SNAKE_CASE ='bias_ih_l1' elif "bias_hh_l1" in name: SCREAMING_SNAKE_CASE ='bias_hh_l1' elif "bias" in name: SCREAMING_SNAKE_CASE ='bias' elif "weight" in name: SCREAMING_SNAKE_CASE ='weight' elif "running_mean" in name: SCREAMING_SNAKE_CASE ='running_mean' elif "running_var" in name: SCREAMING_SNAKE_CASE ='running_var' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE ='num_batches_tracked' else: SCREAMING_SNAKE_CASE =None set_recursively(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) continue if not is_used: unused_weights.append(lowerCAmelCase_ ) logger.warning(F'Unused weights: {unused_weights}' ) @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=None, lowerCAmelCase_=None, ): """simple docstring""" if config_path is not None: SCREAMING_SNAKE_CASE =EncodecConfig.from_pretrained(lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": SCREAMING_SNAKE_CASE =[8, 5, 4, 4] SCREAMING_SNAKE_CASE =[2.2] SCREAMING_SNAKE_CASE =64 SCREAMING_SNAKE_CASE =32000 SCREAMING_SNAKE_CASE =2048 SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =False elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE =[8, 5, 4, 2] SCREAMING_SNAKE_CASE =[3.0, 6.0, 12.0, 24.0] SCREAMING_SNAKE_CASE =48000 SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE ='time_group_norm' SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.01 else: raise ValueError(F'Unknown model name: {model_name}' ) SCREAMING_SNAKE_CASE =EncodecModel(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =EncodecFeatureExtractor( feature_size=config.audio_channels, sampling_rate=config.sampling_rate, chunk_length_s=config.chunk_length_s, overlap=config.overlap, ) feature_extractor.save_pretrained(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights SCREAMING_SNAKE_CASE =original_checkpoint['best_state'] recursively_load_weights(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(lowerCAmelCase_ ) model.push_to_hub(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() parser.add_argument( "--model", default="encodec_24khz", type=str, help="The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.", ) parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) _lowerCamelCase =parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
class a_ : """simple docstring""" def __init__( self : Optional[Any] ): SCREAMING_SNAKE_CASE ={} # Mapping from char to TrieNode SCREAMING_SNAKE_CASE =False def _lowerCAmelCase ( self : Optional[Any] ,snake_case : list[str] ): for word in words: self.insert(snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : str ): SCREAMING_SNAKE_CASE =self for char in word: if char not in curr.nodes: SCREAMING_SNAKE_CASE =TrieNode() SCREAMING_SNAKE_CASE =curr.nodes[char] SCREAMING_SNAKE_CASE =True def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): SCREAMING_SNAKE_CASE =self for char in word: if char not in curr.nodes: return False SCREAMING_SNAKE_CASE =curr.nodes[char] return curr.is_leaf def _lowerCAmelCase ( self : List[str] ,snake_case : str ): def _delete(snake_case : TrieNode ,snake_case : str ,snake_case : int ) -> bool: if index == len(snake_case ): # If word does not exist if not curr.is_leaf: return False SCREAMING_SNAKE_CASE =False return len(curr.nodes ) == 0 SCREAMING_SNAKE_CASE =word[index] SCREAMING_SNAKE_CASE =curr.nodes.get(snake_case ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted SCREAMING_SNAKE_CASE =_delete(snake_case ,snake_case ,index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self ,snake_case ,0 ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if node.is_leaf: print(lowerCAmelCase_, end=' ' ) for key, value in node.nodes.items(): print_words(lowerCAmelCase_, word + key ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE ='banana bananas bandana band apple all beast'.split() SCREAMING_SNAKE_CASE =TrieNode() root.insert_many(lowerCAmelCase_ ) # print_words(root, "") assert all(root.find(lowerCAmelCase_ ) for word in words ) assert root.find('banana' ) assert not root.find('bandanas' ) assert not root.find('apps' ) assert root.find('apple' ) assert root.find('all' ) root.delete('all' ) assert not root.find('all' ) root.delete('banana' ) assert not root.find('banana' ) assert root.find('bananas' ) return True def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" print(str(lowerCAmelCase_ ), 'works!' if passes else 'doesn\'t work :(' ) def snake_case__ ( ): """simple docstring""" assert test_trie() def snake_case__ ( ): """simple docstring""" print_results('Testing trie functionality', test_trie() ) if __name__ == "__main__": main()
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Optional[int] ,snake_case : List[str]=13 ,snake_case : Any=7 ,snake_case : Any=True ,snake_case : Any=True ,snake_case : Union[str, Any]=True ,snake_case : List[str]=True ,snake_case : Union[str, Any]=99 ,snake_case : List[str]=32 ,snake_case : Union[str, Any]=2 ,snake_case : Tuple=4 ,snake_case : List[Any]=37 ,snake_case : Any="gelu" ,snake_case : Tuple=0.1 ,snake_case : List[str]=0.1 ,snake_case : Dict=512 ,snake_case : Optional[int]=16 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=0.02 ,snake_case : Dict=3 ,snake_case : Optional[int]=4 ,snake_case : Optional[int]=None ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =13 SCREAMING_SNAKE_CASE =7 SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =99 SCREAMING_SNAKE_CASE =32 SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =37 SCREAMING_SNAKE_CASE ='gelu' SCREAMING_SNAKE_CASE =0.1 SCREAMING_SNAKE_CASE =0.1 SCREAMING_SNAKE_CASE =512 SCREAMING_SNAKE_CASE =16 SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE =0.02 SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =None def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None if self.use_token_type_ids: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =RoFormerConfig( 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 ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,return_dict=snake_case ,) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Dict ,snake_case : Any ,snake_case : Dict ,snake_case : Optional[Any] ,snake_case : Optional[int] ,snake_case : Optional[Any] ,snake_case : Optional[Any] ,snake_case : int ): SCREAMING_SNAKE_CASE =TFRoFormerModel(config=snake_case ) SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE =[input_ids, input_mask] SCREAMING_SNAKE_CASE =model(snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Tuple ,snake_case : Tuple ,snake_case : Union[str, Any] ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : Any ): SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =TFRoFormerForCausalLM(config=snake_case ) SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE =model(snake_case )['logits'] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) ,[self.batch_size, self.seq_length, self.vocab_size] ) def _lowerCAmelCase ( self : Any ,snake_case : Optional[int] ,snake_case : int ,snake_case : str ,snake_case : Any ,snake_case : Any ,snake_case : Optional[int] ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =TFRoFormerForMaskedLM(config=snake_case ) SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Tuple ,snake_case : Any ,snake_case : str ,snake_case : int ,snake_case : Tuple ,snake_case : Union[str, Any] ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =TFRoFormerForSequenceClassification(config=snake_case ) SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[str] ,snake_case : Optional[int] ,snake_case : str ,snake_case : int ,snake_case : Tuple ,snake_case : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =TFRoFormerForMultipleChoice(config=snake_case ) SCREAMING_SNAKE_CASE =tf.tile(tf.expand_dims(snake_case ,1 ) ,(1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE =tf.tile(tf.expand_dims(snake_case ,1 ) ,(1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE =tf.tile(tf.expand_dims(snake_case ,1 ) ,(1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE ={ 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Dict ,snake_case : Optional[Any] ,snake_case : Optional[int] ,snake_case : Optional[Any] ,snake_case : Optional[int] ,snake_case : int ,snake_case : List[Any] ,snake_case : Dict ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =TFRoFormerForTokenClassification(config=snake_case ) SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[int] ,snake_case : Optional[Any] ,snake_case : Optional[int] ,snake_case : Tuple ,snake_case : Dict ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =TFRoFormerForQuestionAnswering(config=snake_case ) SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE =model(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 _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': TFRoFormerModel, 'fill-mask': TFRoFormerForMaskedLM, 'question-answering': TFRoFormerForQuestionAnswering, 'text-classification': TFRoFormerForSequenceClassification, 'text-generation': TFRoFormerForCausalLM, 'token-classification': TFRoFormerForTokenClassification, 'zero-shot': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : Tuple ,snake_case : Tuple ,snake_case : List[Any] ,snake_case : Optional[Any] ): if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =TFRoFormerModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : Optional[int] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =TFRoFormerModel.from_pretrained('junnyu/roformer_chinese_base' ) self.assertIsNotNone(snake_case ) @require_tf class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =TFRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) SCREAMING_SNAKE_CASE =tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] # TODO Replace vocab size SCREAMING_SNAKE_CASE =50000 SCREAMING_SNAKE_CASE =[1, 6, vocab_size] self.assertEqual(output.shape ,snake_case ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. SCREAMING_SNAKE_CASE =tf.constant( [ [ [-0.12_053_341, -1.0_264_901, 0.29_221_946], [-1.5_133_783, 0.197_433, 0.15_190_607], [-5.0_135_403, -3.900_256, -0.84_038_764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] ,snake_case ,atol=1e-4 ) @require_tf class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = 1e-4 def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =tf.constant([[4, 10]] ) SCREAMING_SNAKE_CASE =TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 ,embedding_dim=6 ) SCREAMING_SNAKE_CASE =emba(input_ids.shape ) SCREAMING_SNAKE_CASE =tf.constant( [[0.0_000, 0.0_000, 0.0_000, 1.0_000, 1.0_000, 1.0_000], [0.8_415, 0.0_464, 0.0_022, 0.5_403, 0.9_989, 1.0_000]] ) tf.debugging.assert_near(snake_case ,snake_case ,atol=self.tolerance ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =tf.constant( [ [0.0_000, 0.0_000, 0.0_000, 0.0_000, 0.0_000], [0.8_415, 0.8_219, 0.8_020, 0.7_819, 0.7_617], [0.9_093, 0.9_364, 0.9_581, 0.9_749, 0.9_870], ] ) SCREAMING_SNAKE_CASE =TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 ,embedding_dim=512 ) emba([2, 16, 512] ) SCREAMING_SNAKE_CASE =emba.weight[:3, :5] tf.debugging.assert_near(snake_case ,snake_case ,atol=self.tolerance ) @require_tf class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = 1e-4 def _lowerCAmelCase ( self : str ): # 2,12,16,64 SCREAMING_SNAKE_CASE =tf.reshape(tf.range(2 * 12 * 16 * 64 ,dtype=tf.floataa ) ,shape=(2, 12, 16, 64) ) / 100 SCREAMING_SNAKE_CASE =-tf.reshape(tf.range(2 * 12 * 16 * 64 ,dtype=tf.floataa ) ,shape=(2, 12, 16, 64) ) / 100 SCREAMING_SNAKE_CASE =TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 ,embedding_dim=64 ) SCREAMING_SNAKE_CASE =embed_positions([2, 16, 768] )[None, None, :, :] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =TFRoFormerSelfAttention.apply_rotary_position_embeddings( snake_case ,snake_case ,snake_case ) SCREAMING_SNAKE_CASE =tf.constant( [ [0.0_000, 0.0_100, 0.0_200, 0.0_300, 0.0_400, 0.0_500, 0.0_600, 0.0_700], [-0.2_012, 0.8_897, 0.0_263, 0.9_401, 0.2_074, 0.9_463, 0.3_481, 0.9_343], [-1.7_057, 0.6_271, -1.2_145, 1.3_897, -0.6_303, 1.7_647, -0.1_173, 1.8_985], [-2.1_731, -1.6_397, -2.7_358, 0.2_854, -2.1_840, 1.7_183, -1.3_018, 2.4_871], [0.2_717, -3.6_173, -2.9_206, -2.1_988, -3.6_638, 0.3_858, -2.9_155, 2.2_980], [3.9_859, -2.1_580, -0.7_984, -4.4_904, -4.1_181, -2.0_252, -4.4_782, 1.1_253], ] ) SCREAMING_SNAKE_CASE =tf.constant( [ [0.0_000, -0.0_100, -0.0_200, -0.0_300, -0.0_400, -0.0_500, -0.0_600, -0.0_700], [0.2_012, -0.8_897, -0.0_263, -0.9_401, -0.2_074, -0.9_463, -0.3_481, -0.9_343], [1.7_057, -0.6_271, 1.2_145, -1.3_897, 0.6_303, -1.7_647, 0.1_173, -1.8_985], [2.1_731, 1.6_397, 2.7_358, -0.2_854, 2.1_840, -1.7_183, 1.3_018, -2.4_871], [-0.2_717, 3.6_173, 2.9_206, 2.1_988, 3.6_638, -0.3_858, 2.9_155, -2.2_980], [-3.9_859, 2.1_580, 0.7_984, 4.4_904, 4.1_181, 2.0_252, 4.4_782, -1.1_253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] ,snake_case ,atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] ,snake_case ,atol=self.tolerance )
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=False ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'vit.embeddings.cls_token'), ('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'vit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE =[(pair[0], pair[1][4:]) if pair[1].startswith('vit' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ] ) return rename_keys def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE ='' else: SCREAMING_SNAKE_CASE ='vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE =state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE =state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE =in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE =in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE =in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE =in_proj_bias[-config.hidden_size :] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowerCAmelCase_, lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =dct.pop(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =val def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE ='http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE =Image.open(requests.get(lowerCAmelCase_, stream=lowerCAmelCase_ ).raw ) return im @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =ViTConfig() SCREAMING_SNAKE_CASE =False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =int(vit_name[-12:-10] ) SCREAMING_SNAKE_CASE =int(vit_name[-9:-6] ) else: SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =int(vit_name[-6:-4] ) SCREAMING_SNAKE_CASE =int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith('tiny' ): SCREAMING_SNAKE_CASE =192 SCREAMING_SNAKE_CASE =768 SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =3 elif vit_name[9:].startswith('small' ): SCREAMING_SNAKE_CASE =384 SCREAMING_SNAKE_CASE =1536 SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =6 else: pass else: if vit_name[4:].startswith('small' ): SCREAMING_SNAKE_CASE =768 SCREAMING_SNAKE_CASE =2304 SCREAMING_SNAKE_CASE =8 SCREAMING_SNAKE_CASE =8 elif vit_name[4:].startswith('base' ): pass elif vit_name[4:].startswith('large' ): SCREAMING_SNAKE_CASE =1024 SCREAMING_SNAKE_CASE =4096 SCREAMING_SNAKE_CASE =24 SCREAMING_SNAKE_CASE =16 elif vit_name[4:].startswith('huge' ): SCREAMING_SNAKE_CASE =1280 SCREAMING_SNAKE_CASE =5120 SCREAMING_SNAKE_CASE =32 SCREAMING_SNAKE_CASE =16 # load original model from timm SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE =timm_model.state_dict() if base_model: remove_classification_head_(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =create_rename_keys(lowerCAmelCase_, lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) read_in_q_k_v(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # load HuggingFace model if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE =ViTModel(lowerCAmelCase_ ).eval() else: SCREAMING_SNAKE_CASE =ViTForImageClassification(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: SCREAMING_SNAKE_CASE =DeiTImageProcessor(size=config.image_size ) else: SCREAMING_SNAKE_CASE =ViTImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE =image_processor(images=prepare_img(), return_tensors='pt' ) SCREAMING_SNAKE_CASE =encoding['pixel_values'] SCREAMING_SNAKE_CASE =model(lowerCAmelCase_ ) if base_model: SCREAMING_SNAKE_CASE =timm_model.forward_features(lowerCAmelCase_ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowerCAmelCase_, outputs.pooler_output, atol=1e-3 ) else: SCREAMING_SNAKE_CASE =timm_model(lowerCAmelCase_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase_, outputs.logits, atol=1e-3 ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F'Saving model {vit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_patch16_224", type=str, help="Name of the ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) _lowerCamelCase =parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
334
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 a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =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 =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =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(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) 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 , SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) 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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, '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 snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Any ,snake_case : UNetaDModel ,snake_case : UNetaDModel ,snake_case : DDPMScheduler ,snake_case : str ,): super().__init__() SCREAMING_SNAKE_CASE =value_function SCREAMING_SNAKE_CASE =unet SCREAMING_SNAKE_CASE =scheduler SCREAMING_SNAKE_CASE =env SCREAMING_SNAKE_CASE =env.get_dataset() SCREAMING_SNAKE_CASE ={} for key in self.data.keys(): try: SCREAMING_SNAKE_CASE =self.data[key].mean() except: # noqa: E722 pass SCREAMING_SNAKE_CASE ={} for key in self.data.keys(): try: SCREAMING_SNAKE_CASE =self.data[key].std() except: # noqa: E722 pass SCREAMING_SNAKE_CASE =env.observation_space.shape[0] SCREAMING_SNAKE_CASE =env.action_space.shape[0] def _lowerCAmelCase ( self : List[str] ,snake_case : str ,snake_case : List[str] ): return (x_in - self.means[key]) / self.stds[key] def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[int] ,snake_case : Any ): return x_in * self.stds[key] + self.means[key] def _lowerCAmelCase ( self : str ,snake_case : Optional[Any] ): if type(snake_case ) is dict: return {k: self.to_torch(snake_case ) for k, v in x_in.items()} elif torch.is_tensor(snake_case ): return x_in.to(self.unet.device ) return torch.tensor(snake_case ,device=self.unet.device ) def _lowerCAmelCase ( self : Dict ,snake_case : List[Any] ,snake_case : Optional[int] ,snake_case : Optional[int] ): for key, val in cond.items(): SCREAMING_SNAKE_CASE =val.clone() return x_in def _lowerCAmelCase ( self : str ,snake_case : str ,snake_case : str ,snake_case : Tuple ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =x.shape[0] SCREAMING_SNAKE_CASE =None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model SCREAMING_SNAKE_CASE =torch.full((batch_size,) ,snake_case ,device=self.unet.device ,dtype=torch.long ) for _ in range(snake_case ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models SCREAMING_SNAKE_CASE =self.value_function(x.permute(0 ,2 ,1 ) ,snake_case ).sample SCREAMING_SNAKE_CASE =torch.autograd.grad([y.sum()] ,[x] )[0] SCREAMING_SNAKE_CASE =self.scheduler._get_variance(snake_case ) SCREAMING_SNAKE_CASE =torch.exp(0.5 * posterior_variance ) SCREAMING_SNAKE_CASE =model_std * grad SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =x.detach() SCREAMING_SNAKE_CASE =x + scale * grad SCREAMING_SNAKE_CASE =self.reset_xa(snake_case ,snake_case ,self.action_dim ) SCREAMING_SNAKE_CASE =self.unet(x.permute(0 ,2 ,1 ) ,snake_case ).sample.permute(0 ,2 ,1 ) # TODO: verify deprecation of this kwarg SCREAMING_SNAKE_CASE =self.scheduler.step(snake_case ,snake_case ,snake_case ,predict_epsilon=snake_case )['prev_sample'] # apply conditions to the trajectory (set the initial state) SCREAMING_SNAKE_CASE =self.reset_xa(snake_case ,snake_case ,self.action_dim ) SCREAMING_SNAKE_CASE =self.to_torch(snake_case ) return x, y def __call__( self : Dict ,snake_case : Tuple ,snake_case : List[Any]=64 ,snake_case : Any=32 ,snake_case : List[str]=2 ,snake_case : Union[str, Any]=0.1 ): # normalize the observations and create batch dimension SCREAMING_SNAKE_CASE =self.normalize(snake_case ,'observations' ) SCREAMING_SNAKE_CASE =obs[None].repeat(snake_case ,axis=0 ) SCREAMING_SNAKE_CASE ={0: self.to_torch(snake_case )} SCREAMING_SNAKE_CASE =(batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) SCREAMING_SNAKE_CASE =randn_tensor(snake_case ,device=self.unet.device ) SCREAMING_SNAKE_CASE =self.reset_xa(snake_case ,snake_case ,self.action_dim ) SCREAMING_SNAKE_CASE =self.to_torch(snake_case ) # run the diffusion process SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.run_diffusion(snake_case ,snake_case ,snake_case ,snake_case ) # sort output trajectories by value SCREAMING_SNAKE_CASE =y.argsort(0 ,descending=snake_case ).squeeze() SCREAMING_SNAKE_CASE =x[sorted_idx] SCREAMING_SNAKE_CASE =sorted_values[:, :, : self.action_dim] SCREAMING_SNAKE_CASE =actions.detach().cpu().numpy() SCREAMING_SNAKE_CASE =self.de_normalize(snake_case ,key='actions' ) # select the action with the highest value if y is not None: SCREAMING_SNAKE_CASE =0 else: # if we didn't run value guiding, select a random action SCREAMING_SNAKE_CASE =np.random.randint(0 ,snake_case ) SCREAMING_SNAKE_CASE =denorm_actions[selected_index, 0] return denorm_actions
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels _lowerCamelCase =object() # For specifying empty leaf dict `{}` _lowerCamelCase =object() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(lowerCAmelCase_ ) - len(lowerCAmelCase_ ) + 1 ): SCREAMING_SNAKE_CASE =[x.match(lowerCAmelCase_ ) for x, y in zip(lowerCAmelCase_, ks[i:] )] if matches and all(lowerCAmelCase_ ): return True return False def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" def replace(lowerCAmelCase_, lowerCAmelCase_ ): for rule, replacement in rules: if _match(lowerCAmelCase_, lowerCAmelCase_ ): return replacement return val return replace def snake_case__ ( ): """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P('mp', lowerCAmelCase_ )), (("transformer", "wte", "embedding"), P('mp', lowerCAmelCase_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCAmelCase_, 'mp' )), (("attention", "out_proj", "kernel"), P('mp', lowerCAmelCase_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowerCAmelCase_, 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp', lowerCAmelCase_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =_get_partition_rules() SCREAMING_SNAKE_CASE =_replacement_rules(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={k: _unmatched for k in flatten_dict(lowerCAmelCase_ )} SCREAMING_SNAKE_CASE ={k: replace(lowerCAmelCase_, lowerCAmelCase_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowerCAmelCase_ ) )
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
import warnings from ..trainer import Trainer from ..utils import logging _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] ,snake_case : str=None ,**snake_case : Dict ): warnings.warn( '`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ' 'instead.' ,snake_case ,) super().__init__(args=snake_case ,**snake_case )
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _lowerCamelCase =[ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ["memory_attention", "encoder_attn"], ["attention", "attn"], ["/", "."], [".LayerNorm.gamma", "_layer_norm.weight"], [".LayerNorm.beta", "_layer_norm.bias"], ["r.layer_", "r.layers."], ["output_proj", "out_proj"], ["ffn.dense_1.", "fc2."], ["ffn.dense.", "fc1."], ["ffn_layer_norm", "final_layer_norm"], ["kernel", "weight"], ["encoder_layer_norm.", "encoder.layer_norm."], ["decoder_layer_norm.", "decoder.layer_norm."], ["embeddings.weights", "shared.weight"], ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" for pegasus_name, hf_name in PATTERNS: SCREAMING_SNAKE_CASE =k.replace(lowerCAmelCase_, lowerCAmelCase_ ) return k def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =DEFAULTS.copy() cfg_kwargs.update(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =PegasusConfig(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =PegasusForConditionalGeneration(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch_model.model.state_dict() SCREAMING_SNAKE_CASE ={} for k, v in tf_weights.items(): SCREAMING_SNAKE_CASE =rename_state_dict_key(lowerCAmelCase_ ) if new_k not in sd: raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' ) if "dense" in k or "proj" in new_k: SCREAMING_SNAKE_CASE =v.T SCREAMING_SNAKE_CASE =torch.tensor(lowerCAmelCase_, dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F'{new_k}, {k}, {v.shape}, {sd[new_k].shape}' # make sure embedding.padding_idx is respected SCREAMING_SNAKE_CASE =torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1] ) SCREAMING_SNAKE_CASE =mapping['shared.weight'] SCREAMING_SNAKE_CASE =mapping['shared.weight'] SCREAMING_SNAKE_CASE ={k: torch.zeros_like(lowerCAmelCase_ ) for k, v in sd.items() if k.endswith('bias' ) and k not in mapping} mapping.update(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =torch_model.model.load_state_dict(lowerCAmelCase_, strict=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =[ k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight'] ] assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}' assert extra == [], F'no matches found for the following tf keys {extra}' return torch_model def snake_case__ ( lowerCAmelCase_="./ckpt/aeslc/model.ckpt-32000" ): """simple docstring""" SCREAMING_SNAKE_CASE =tf.train.list_variables(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =['Adafactor', 'global_step'] for name, shape in tqdm(lowerCAmelCase_, desc='converting tf checkpoint to dict' ): SCREAMING_SNAKE_CASE =any(pat in name for pat in ignore_name ) if skip_key: continue SCREAMING_SNAKE_CASE =tf.train.load_variable(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =array return tf_weights def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =Path(lowerCAmelCase_ ).parent.name SCREAMING_SNAKE_CASE =task_specific_params[F'summarization_{dataset}']['max_position_embeddings'] SCREAMING_SNAKE_CASE =PegasusTokenizer.from_pretrained('sshleifer/pegasus', model_max_length=lowerCAmelCase_ ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(lowerCAmelCase_ ) # convert model SCREAMING_SNAKE_CASE =get_tf_weights_as_numpy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =task_specific_params[F'summarization_{dataset}'] if dataset == "large": SCREAMING_SNAKE_CASE =task_specific_params SCREAMING_SNAKE_CASE =convert_pegasus(lowerCAmelCase_, lowerCAmelCase_ ) torch_model.save_pretrained(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch_model.state_dict() sd.pop('model.decoder.embed_positions.weight' ) sd.pop('model.encoder.embed_positions.weight' ) torch.save(lowerCAmelCase_, Path(lowerCAmelCase_ ) / 'pytorch_model.bin' ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("save_dir", default=None, type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() if args.save_dir is None: _lowerCamelCase =Path(args.tf_ckpt_path).parent.name _lowerCamelCase =os.path.join("pegasus", dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 _lowerCamelCase =get_tests_dir("fixtures") class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : str ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" @classmethod def _lowerCAmelCase ( cls : Optional[int] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : List[Any] ): try: delete_repo(token=cls._token ,repo_id='test-feature-extractor' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-feature-extractor-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-feature-extractor' ) except HTTPError: pass def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained(snake_case ) feature_extractor.push_to_hub('test-feature-extractor' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) # Reset repo delete_repo(token=self._token ,repo_id='test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( snake_case ,repo_id='test-feature-extractor' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained(f'{USER}/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained(snake_case ) feature_extractor.push_to_hub('valid_org/test-feature-extractor' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( snake_case ,repo_id='valid_org/test-feature-extractor-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) def _lowerCAmelCase ( self : Dict ): CustomFeatureExtractor.register_for_auto_class() SCREAMING_SNAKE_CASE =CustomFeatureExtractor.from_pretrained(snake_case ) feature_extractor.push_to_hub('test-dynamic-feature-extractor' ,use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map ,{'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor'} ,) SCREAMING_SNAKE_CASE =AutoFeatureExtractor.from_pretrained( f'{USER}/test-dynamic-feature-extractor' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ ,'CustomFeatureExtractor' )
334
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_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =seq_length SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_input_mask SCREAMING_SNAKE_CASE =use_token_type_ids SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_choices SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Optional[int] ): 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 _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=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 _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase ={ "configuration_data2vec_audio": ["DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecAudioConfig"], "configuration_data2vec_text": [ "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecTextConfig", "Data2VecTextOnnxConfig", ], "configuration_data2vec_vision": [ "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecVisionConfig", "Data2VecVisionOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecAudioForAudioFrameClassification", "Data2VecAudioForCTC", "Data2VecAudioForSequenceClassification", "Data2VecAudioForXVector", "Data2VecAudioModel", "Data2VecAudioPreTrainedModel", ] _lowerCamelCase =[ "DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecTextForCausalLM", "Data2VecTextForMaskedLM", "Data2VecTextForMultipleChoice", "Data2VecTextForQuestionAnswering", "Data2VecTextForSequenceClassification", "Data2VecTextForTokenClassification", "Data2VecTextModel", "Data2VecTextPreTrainedModel", ] _lowerCamelCase =[ "DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecVisionForImageClassification", "Data2VecVisionForMaskedImageModeling", "Data2VecVisionForSemanticSegmentation", "Data2VecVisionModel", "Data2VecVisionPreTrainedModel", ] if is_tf_available(): _lowerCamelCase =[ "TFData2VecVisionForImageClassification", "TFData2VecVisionForSemanticSegmentation", "TFData2VecVisionModel", "TFData2VecVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _lowerCamelCase ={ "vocab_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json" }, "merges_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt" }, } _lowerCamelCase ={"allegro/herbert-base-cased": 5_14} _lowerCamelCase ={} class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = HerbertTokenizer def __init__( self : Optional[int] ,snake_case : Any=None ,snake_case : str=None ,snake_case : Optional[Any]=None ,snake_case : List[str]="<s>" ,snake_case : Union[str, Any]="<unk>" ,snake_case : Dict="<pad>" ,snake_case : List[Any]="<mask>" ,snake_case : Any="</s>" ,**snake_case : Dict ,): super().__init__( snake_case ,snake_case ,tokenizer_file=snake_case ,cls_token=snake_case ,unk_token=snake_case ,pad_token=snake_case ,mask_token=snake_case ,sep_token=snake_case ,**snake_case ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowerCAmelCase ( self : List[Any] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ,snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case ,token_ids_a=snake_case ,already_has_special_tokens=snake_case ) if token_ids_a is None: return [1] + ([0] * len(snake_case )) + [1] return [1] + ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1] def _lowerCAmelCase ( self : str ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.sep_token_id] SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCAmelCase ( self : int ,snake_case : str ,snake_case : Optional[str] = None ): SCREAMING_SNAKE_CASE =self._tokenizer.model.save(snake_case ,name=snake_case ) return tuple(snake_case )
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
from __future__ import annotations import math def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if len(lowerCAmelCase_ ) != 2 or len(a[0] ) != 2 or len(lowerCAmelCase_ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) SCREAMING_SNAKE_CASE =[ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCAmelCase_ ) ) ] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCAmelCase_ ) ) ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if len(lowerCAmelCase_ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =matrix_length // 2 SCREAMING_SNAKE_CASE =[[a[i][j] for j in range(lowerCAmelCase_, lowerCAmelCase_ )] for i in range(lowerCAmelCase_ )] SCREAMING_SNAKE_CASE =[ [a[i][j] for j in range(lowerCAmelCase_, lowerCAmelCase_ )] for i in range(lowerCAmelCase_, lowerCAmelCase_ ) ] SCREAMING_SNAKE_CASE =[[a[i][j] for j in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ )] SCREAMING_SNAKE_CASE =[[a[i][j] for j in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_, lowerCAmelCase_ )] return top_left, top_right, bot_left, bot_right def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return len(lowerCAmelCase_ ), len(matrix[0] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" print('\n'.join(str(lowerCAmelCase_ ) for line in matrix ) ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if matrix_dimensions(lowerCAmelCase_ ) == (2, 2): return default_matrix_multiplication(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =split_matrix(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =split_matrix(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =actual_strassen(lowerCAmelCase_, matrix_subtraction(lowerCAmelCase_, lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =actual_strassen(matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ), lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =actual_strassen(matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ), lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =actual_strassen(lowerCAmelCase_, matrix_subtraction(lowerCAmelCase_, lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =actual_strassen(matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ), matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =actual_strassen(matrix_subtraction(lowerCAmelCase_, lowerCAmelCase_ ), matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =actual_strassen(matrix_subtraction(lowerCAmelCase_, lowerCAmelCase_ ), matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ) ) SCREAMING_SNAKE_CASE =matrix_addition(matrix_subtraction(matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ), lowerCAmelCase_ ), lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =matrix_subtraction(matrix_subtraction(matrix_addition(lowerCAmelCase_, lowerCAmelCase_ ), lowerCAmelCase_ ), lowerCAmelCase_ ) # construct the new matrix from our 4 quadrants SCREAMING_SNAKE_CASE =[] for i in range(len(lowerCAmelCase_ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCAmelCase_ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if matrix_dimensions(lowerCAmelCase_ )[1] != matrix_dimensions(lowerCAmelCase_ )[0]: SCREAMING_SNAKE_CASE =( 'Unable to multiply these matrices, please check the dimensions.\n' F'Matrix A: {matrixa}\n' F'Matrix B: {matrixa}' ) raise Exception(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =matrix_dimensions(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =matrix_dimensions(lowerCAmelCase_ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] SCREAMING_SNAKE_CASE =max(*lowerCAmelCase_, *lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =int(math.pow(2, math.ceil(math.loga(lowerCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE =matrixa SCREAMING_SNAKE_CASE =matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0, lowerCAmelCase_ ): if i < dimensiona[0]: for _ in range(dimensiona[1], lowerCAmelCase_ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1], lowerCAmelCase_ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) SCREAMING_SNAKE_CASE =actual_strassen(lowerCAmelCase_, lowerCAmelCase_ ) # Removing the additional zeros for i in range(0, lowerCAmelCase_ ): if i < dimensiona[0]: for _ in range(dimensiona[1], lowerCAmelCase_ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": _lowerCamelCase =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] _lowerCamelCase =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging _lowerCamelCase =logging.get_logger(__name__) class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = None @staticmethod def _lowerCAmelCase ( ): raise NotImplementedError def _lowerCAmelCase ( self : Dict ,snake_case : Any ,snake_case : int ,snake_case : str ,**snake_case : Optional[Any] ): raise NotImplementedError def _lowerCAmelCase ( self : str ,snake_case : List[Any] ): raise NotImplementedError def _lowerCAmelCase ( self : List[Any] ): if not self.is_available(): raise RuntimeError( f'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' ) @classmethod def _lowerCAmelCase ( cls : Optional[int] ): return f'`pip install {cls.pip_package or cls.name}`' class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'optuna' @staticmethod def _lowerCAmelCase ( ): return is_optuna_available() def _lowerCAmelCase ( self : int ,snake_case : str ,snake_case : int ,snake_case : str ,**snake_case : List[str] ): return run_hp_search_optuna(snake_case ,snake_case ,snake_case ,**snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Optional[int] ): return default_hp_space_optuna(snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'ray' __UpperCAmelCase = '\'ray[tune]\'' @staticmethod def _lowerCAmelCase ( ): return is_ray_available() def _lowerCAmelCase ( self : int ,snake_case : Union[str, Any] ,snake_case : int ,snake_case : str ,**snake_case : List[str] ): return run_hp_search_ray(snake_case ,snake_case ,snake_case ,**snake_case ) def _lowerCAmelCase ( self : str ,snake_case : int ): return default_hp_space_ray(snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'sigopt' @staticmethod def _lowerCAmelCase ( ): return is_sigopt_available() def _lowerCAmelCase ( self : int ,snake_case : Optional[Any] ,snake_case : int ,snake_case : str ,**snake_case : Union[str, Any] ): return run_hp_search_sigopt(snake_case ,snake_case ,snake_case ,**snake_case ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[Any] ): return default_hp_space_sigopt(snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'wandb' @staticmethod def _lowerCAmelCase ( ): return is_wandb_available() def _lowerCAmelCase ( self : List[Any] ,snake_case : Tuple ,snake_case : int ,snake_case : str ,**snake_case : List[str] ): return run_hp_search_wandb(snake_case ,snake_case ,snake_case ,**snake_case ) def _lowerCAmelCase ( self : Tuple ,snake_case : Any ): return default_hp_space_wandb(snake_case ) _lowerCamelCase ={ HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =[backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCAmelCase_ ) > 0: SCREAMING_SNAKE_CASE =available_backends[0].name if len(lowerCAmelCase_ ) > 1: logger.info( F'{len(lowerCAmelCase_ )} hyperparameter search backends available. Using {name} as the default.' ) return name raise RuntimeError( 'No hyperparameter search backend available.\n' + '\n'.join( F' - To install {backend.name} run {backend.pip_install()}' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,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 ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =config_and_inputs SCREAMING_SNAKE_CASE ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) SCREAMING_SNAKE_CASE =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE =['pixel_values'] self.assertListEqual(arg_names[:1] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
from __future__ import annotations from typing import Any class a_ ( lowerCamelCase_ ): """simple docstring""" pass class a_ : """simple docstring""" def __init__( self : Union[str, Any] ,snake_case : Any ): SCREAMING_SNAKE_CASE =data SCREAMING_SNAKE_CASE =None def __iter__( self : List[Any] ): SCREAMING_SNAKE_CASE =self SCREAMING_SNAKE_CASE =[] while node: if node in visited: raise ContainsLoopError visited.append(snake_case ) yield node.data SCREAMING_SNAKE_CASE =node.next_node @property def _lowerCAmelCase ( self : Union[str, Any] ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase =Node(1) _lowerCamelCase =Node(2) _lowerCamelCase =Node(3) _lowerCamelCase =Node(4) print(root_node.has_loop) # False _lowerCamelCase =root_node.next_node print(root_node.has_loop) # True _lowerCamelCase =Node(5) _lowerCamelCase =Node(6) _lowerCamelCase =Node(5) _lowerCamelCase =Node(6) print(root_node.has_loop) # False _lowerCamelCase =Node(1) print(root_node.has_loop) # False
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _lowerCamelCase ={ "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "MEGA_PRETRAINED_MODEL_ARCHIVE_LIST", "MegaForCausalLM", "MegaForMaskedLM", "MegaForMultipleChoice", "MegaForQuestionAnswering", "MegaForSequenceClassification", "MegaForTokenClassification", "MegaModel", "MegaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE =load_dataset('glue', 'mrpc' ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowerCAmelCase_, max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE =datasets.map( lowerCAmelCase_, batched=lowerCAmelCase_, remove_columns=['idx', 'sentence1', 'sentence2'], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE =16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE =8 else: SCREAMING_SNAKE_CASE =None return tokenizer.pad( lowerCAmelCase_, padding='longest', max_length=lowerCAmelCase_, pad_to_multiple_of=lowerCAmelCase_, return_tensors='pt', ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['train'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['validation'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if os.environ.get('TESTING_MOCKED_DATALOADERS', lowerCAmelCase_ ) == "1": SCREAMING_SNAKE_CASE =2 # Initialize accelerator SCREAMING_SNAKE_CASE =Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE =config['lr'] SCREAMING_SNAKE_CASE =int(config['num_epochs'] ) SCREAMING_SNAKE_CASE =int(config['seed'] ) SCREAMING_SNAKE_CASE =int(config['batch_size'] ) SCREAMING_SNAKE_CASE =evaluate.load('glue', 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE =AutoModelForSequenceClassification.from_pretrained('bert-base-cased', return_dict=lowerCAmelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE =model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE =AdamW(params=model.parameters(), lr=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =get_dataloaders(lowerCAmelCase_, lowerCAmelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE =get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_, num_warmup_steps=100, num_training_steps=(len(lowerCAmelCase_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.prepare( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCAmelCase_, references=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:', lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision', type=lowerCAmelCase_, default=lowerCAmelCase_, choices=['no', 'fp16', 'bf16', 'fp8'], help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.', ) parser.add_argument('--cpu', action='store_true', help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE ={'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCAmelCase_, lowerCAmelCase_ ) if __name__ == "__main__": main()
334
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "xlm-mlm-en-2048": "https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json", "xlm-mlm-ende-1024": "https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json", "xlm-mlm-enfr-1024": "https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json", "xlm-mlm-enro-1024": "https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json", "xlm-mlm-tlm-xnli15-1024": "https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json", "xlm-mlm-xnli15-1024": "https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json", "xlm-clm-enfr-1024": "https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json", "xlm-clm-ende-1024": "https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json", "xlm-mlm-17-1280": "https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json", "xlm-mlm-100-1280": "https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'xlm' __UpperCAmelCase = { 'hidden_size': 'emb_dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', 'n_words': 'vocab_size', # For backward compatibility } def __init__( self : Optional[Any] ,snake_case : Optional[Any]=30145 ,snake_case : Optional[int]=2048 ,snake_case : List[Any]=12 ,snake_case : List[str]=16 ,snake_case : Dict=0.1 ,snake_case : int=0.1 ,snake_case : Union[str, Any]=True ,snake_case : Optional[int]=False ,snake_case : Any=False ,snake_case : Tuple=False ,snake_case : Union[str, Any]=1 ,snake_case : Any=True ,snake_case : Tuple=512 ,snake_case : Dict=2048**-0.5 ,snake_case : Union[str, Any]=1e-12 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=0 ,snake_case : int=1 ,snake_case : Optional[Any]=2 ,snake_case : Optional[int]=3 ,snake_case : Union[str, Any]=5 ,snake_case : List[str]=True ,snake_case : Union[str, Any]="first" ,snake_case : Optional[int]=True ,snake_case : int=None ,snake_case : List[Any]=True ,snake_case : str=0.1 ,snake_case : List[Any]=5 ,snake_case : Optional[Any]=5 ,snake_case : Optional[Any]=0 ,snake_case : List[Any]=0 ,snake_case : List[str]=2 ,snake_case : Optional[Any]=0 ,**snake_case : Any ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =emb_dim SCREAMING_SNAKE_CASE =n_layers SCREAMING_SNAKE_CASE =n_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =gelu_activation SCREAMING_SNAKE_CASE =sinusoidal_embeddings SCREAMING_SNAKE_CASE =causal SCREAMING_SNAKE_CASE =asm SCREAMING_SNAKE_CASE =n_langs SCREAMING_SNAKE_CASE =use_lang_emb SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =bos_index SCREAMING_SNAKE_CASE =eos_index SCREAMING_SNAKE_CASE =pad_index SCREAMING_SNAKE_CASE =unk_index SCREAMING_SNAKE_CASE =mask_index SCREAMING_SNAKE_CASE =is_encoder SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =embed_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =summary_type SCREAMING_SNAKE_CASE =summary_use_proj SCREAMING_SNAKE_CASE =summary_activation SCREAMING_SNAKE_CASE =summary_proj_to_labels SCREAMING_SNAKE_CASE =summary_first_dropout SCREAMING_SNAKE_CASE =start_n_top SCREAMING_SNAKE_CASE =end_n_top SCREAMING_SNAKE_CASE =mask_token_id SCREAMING_SNAKE_CASE =lang_id if "n_words" in kwargs: SCREAMING_SNAKE_CASE =kwargs['n_words'] super().__init__(pad_token_id=snake_case ,bos_token_id=snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" @property def _lowerCAmelCase ( self : Dict ): if self.task == "multiple-choice": SCREAMING_SNAKE_CASE ={0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE ={0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class a_ ( unittest.TestCase ): """simple docstring""" def __init__( self : int ,snake_case : str ,snake_case : Union[str, Any]=7 ,snake_case : int=3 ,snake_case : int=30 ,snake_case : Tuple=400 ,snake_case : str=True ,snake_case : Optional[Any]=None ,snake_case : Optional[int]=True ,snake_case : Dict=[0.5, 0.5, 0.5] ,snake_case : List[str]=[0.5, 0.5, 0.5] ,snake_case : Dict=True ,snake_case : int=1 / 255 ,snake_case : List[str]=True ,): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE =size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =min_resolution SCREAMING_SNAKE_CASE =max_resolution SCREAMING_SNAKE_CASE =do_resize SCREAMING_SNAKE_CASE =size SCREAMING_SNAKE_CASE =do_normalize SCREAMING_SNAKE_CASE =image_mean SCREAMING_SNAKE_CASE =image_std SCREAMING_SNAKE_CASE =do_rescale SCREAMING_SNAKE_CASE =rescale_factor SCREAMING_SNAKE_CASE =do_pad def _lowerCAmelCase ( self : Any ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : List[str]=False ): if not batched: SCREAMING_SNAKE_CASE =image_inputs[0] if isinstance(snake_case ,Image.Image ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =image.size else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE =int(self.size['shortest_edge'] * h / w ) SCREAMING_SNAKE_CASE =self.size['shortest_edge'] elif w > h: SCREAMING_SNAKE_CASE =self.size['shortest_edge'] SCREAMING_SNAKE_CASE =int(self.size['shortest_edge'] * w / h ) else: SCREAMING_SNAKE_CASE =self.size['shortest_edge'] SCREAMING_SNAKE_CASE =self.size['shortest_edge'] else: SCREAMING_SNAKE_CASE =[] for image in image_inputs: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) SCREAMING_SNAKE_CASE =max(snake_case ,key=lambda snake_case : item[0] )[0] SCREAMING_SNAKE_CASE =max(snake_case ,key=lambda snake_case : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = YolosImageProcessor if is_vision_available() else None def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =YolosImageProcessingTester(self ) @property def _lowerCAmelCase ( self : Dict ): return self.image_processor_tester.prepare_image_processor_dict() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case ,'image_mean' ) ) self.assertTrue(hasattr(snake_case ,'image_std' ) ) self.assertTrue(hasattr(snake_case ,'do_normalize' ) ) self.assertTrue(hasattr(snake_case ,'do_resize' ) ) self.assertTrue(hasattr(snake_case ,'size' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad ,snake_case ) SCREAMING_SNAKE_CASE =self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,max_size=84 ,pad_and_return_pixel_mask=snake_case ) self.assertEqual(image_processor.size ,{'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad ,snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): pass def _lowerCAmelCase ( self : Any ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.image_processor_tester.get_expected_values(snake_case ) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.image_processor_tester.get_expected_values(snake_case ,batched=snake_case ) SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def _lowerCAmelCase ( self : int ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,numpify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.image_processor_tester.get_expected_values(snake_case ) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.image_processor_tester.get_expected_values(snake_case ,batched=snake_case ) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def _lowerCAmelCase ( self : Optional[Any] ): # Initialize image_processing SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE =image_processing(image_inputs[0] ,return_tensors='pt' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.image_processor_tester.get_expected_values(snake_case ) self.assertEqual( encoded_images.shape ,(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,) # Test batched SCREAMING_SNAKE_CASE =image_processing(snake_case ,return_tensors='pt' ).pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.image_processor_tester.get_expected_values(snake_case ,batched=snake_case ) self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) ,) def _lowerCAmelCase ( self : Optional[int] ): # Initialize image_processings SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE =self.image_processing_class(do_resize=snake_case ,do_normalize=snake_case ,do_rescale=snake_case ) # create random PyTorch tensors SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester ,equal_resolution=snake_case ,torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case ,torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors SCREAMING_SNAKE_CASE =image_processing_a.pad(snake_case ,return_tensors='pt' ) SCREAMING_SNAKE_CASE =image_processing_a(snake_case ,return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] ,encoded_images['pixel_values'] ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : Optional[int] ): # prepare image and target SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' ,'r' ) as f: SCREAMING_SNAKE_CASE =json.loads(f.read() ) SCREAMING_SNAKE_CASE ={'image_id': 39769, 'annotations': target} # encode them SCREAMING_SNAKE_CASE =YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) SCREAMING_SNAKE_CASE =image_processing(images=snake_case ,annotations=snake_case ,return_tensors='pt' ) # verify pixel values SCREAMING_SNAKE_CASE =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,snake_case ,atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE =torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,snake_case ) ) # verify boxes SCREAMING_SNAKE_CASE =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,snake_case ,atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,snake_case ) ) # verify is_crowd SCREAMING_SNAKE_CASE =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,snake_case ) ) # verify class_labels SCREAMING_SNAKE_CASE =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,snake_case ) ) # verify orig_size SCREAMING_SNAKE_CASE =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,snake_case ) ) # verify size SCREAMING_SNAKE_CASE =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,snake_case ) ) @slow def _lowerCAmelCase ( self : Optional[int] ): # prepare image, target and masks_path SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' ,'r' ) as f: SCREAMING_SNAKE_CASE =json.loads(f.read() ) SCREAMING_SNAKE_CASE ={'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} SCREAMING_SNAKE_CASE =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them SCREAMING_SNAKE_CASE =YolosImageProcessor(format='coco_panoptic' ) SCREAMING_SNAKE_CASE =image_processing(images=snake_case ,annotations=snake_case ,masks_path=snake_case ,return_tensors='pt' ) # verify pixel values SCREAMING_SNAKE_CASE =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] ,snake_case ,atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE =torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] ,snake_case ) ) # verify boxes SCREAMING_SNAKE_CASE =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] ,snake_case ,atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] ,snake_case ) ) # verify is_crowd SCREAMING_SNAKE_CASE =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] ,snake_case ) ) # verify class_labels SCREAMING_SNAKE_CASE =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] ,snake_case ) ) # verify masks SCREAMING_SNAKE_CASE =822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() ,snake_case ) # verify orig_size SCREAMING_SNAKE_CASE =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] ,snake_case ) ) # verify size SCREAMING_SNAKE_CASE =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] ,snake_case ) )
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: _lowerCamelCase =None _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} _lowerCamelCase ={ "vocab_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model", }, "tokenizer_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/tokenizer.json", }, } _lowerCamelCase ={ "camembert-base": 5_12, } _lowerCamelCase ="▁" class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] __UpperCAmelCase = CamembertTokenizer def __init__( self : List[str] ,snake_case : str=None ,snake_case : Dict=None ,snake_case : int="<s>" ,snake_case : Optional[int]="</s>" ,snake_case : Optional[Any]="</s>" ,snake_case : Union[str, Any]="<s>" ,snake_case : Optional[int]="<unk>" ,snake_case : Optional[Any]="<pad>" ,snake_case : str="<mask>" ,snake_case : Tuple=["<s>NOTUSED", "</s>NOTUSED"] ,**snake_case : Any ,): # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE =AddedToken(snake_case ,lstrip=snake_case ,rstrip=snake_case ) if isinstance(snake_case ,snake_case ) else mask_token super().__init__( snake_case ,tokenizer_file=snake_case ,bos_token=snake_case ,eos_token=snake_case ,sep_token=snake_case ,cls_token=snake_case ,unk_token=snake_case ,pad_token=snake_case ,mask_token=snake_case ,additional_special_tokens=snake_case ,**snake_case ,) SCREAMING_SNAKE_CASE =vocab_file SCREAMING_SNAKE_CASE =False if not self.vocab_file else True def _lowerCAmelCase ( self : Dict ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowerCAmelCase ( self : int ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.sep_token_id] SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _lowerCAmelCase ( self : str ,snake_case : str ,snake_case : Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(snake_case ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE =os.path.join( snake_case ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case ): copyfile(self.vocab_file ,snake_case ) return (out_vocab_file,)
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
from __future__ import annotations import numpy as np def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return np.maximum(0, lowerCAmelCase_ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
from __future__ import annotations from functools import lru_cache from math import ceil _lowerCamelCase =1_00 _lowerCamelCase =set(range(3, NUM_PRIMES, 2)) primes.add(2) _lowerCamelCase =42 for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} SCREAMING_SNAKE_CASE =set() SCREAMING_SNAKE_CASE =42 SCREAMING_SNAKE_CASE =42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def snake_case__ ( lowerCAmelCase_ = 5000 ): """simple docstring""" for number_to_partition in range(1, lowerCAmelCase_ ): if len(partition(lowerCAmelCase_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f'{solution() = }')
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE =load_dataset('glue', 'mrpc' ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowerCAmelCase_, max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE =datasets.map( lowerCAmelCase_, batched=lowerCAmelCase_, remove_columns=['idx', 'sentence1', 'sentence2'], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE =16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE =8 else: SCREAMING_SNAKE_CASE =None return tokenizer.pad( lowerCAmelCase_, padding='longest', max_length=lowerCAmelCase_, pad_to_multiple_of=lowerCAmelCase_, return_tensors='pt', ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['train'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['validation'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if os.environ.get('TESTING_MOCKED_DATALOADERS', lowerCAmelCase_ ) == "1": SCREAMING_SNAKE_CASE =2 # Initialize accelerator SCREAMING_SNAKE_CASE =Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE =config['lr'] SCREAMING_SNAKE_CASE =int(config['num_epochs'] ) SCREAMING_SNAKE_CASE =int(config['seed'] ) SCREAMING_SNAKE_CASE =int(config['batch_size'] ) SCREAMING_SNAKE_CASE =evaluate.load('glue', 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE =AutoModelForSequenceClassification.from_pretrained('bert-base-cased', return_dict=lowerCAmelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE =model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE =AdamW(params=model.parameters(), lr=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =get_dataloaders(lowerCAmelCase_, lowerCAmelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE =get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_, num_warmup_steps=100, num_training_steps=(len(lowerCAmelCase_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.prepare( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCAmelCase_, references=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:', lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision', type=lowerCAmelCase_, default=lowerCAmelCase_, choices=['no', 'fp16', 'bf16', 'fp8'], help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.', ) parser.add_argument('--cpu', action='store_true', help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE ={'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCAmelCase_, lowerCAmelCase_ ) if __name__ == "__main__": main()
334
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 a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =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 =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =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(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) 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 , SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) 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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, '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 snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE =os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) SCREAMING_SNAKE_CASE =os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =f'\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n '.split() SCREAMING_SNAKE_CASE =[sys.executable] + distributed_args execute_subprocess_async(snake_case ,env=os.environ.copy() )
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if digit_amount > 0: return round(number - int(lowerCAmelCase_ ), lowerCAmelCase_ ) return number - int(lowerCAmelCase_ ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class a_ : """simple docstring""" @staticmethod def _lowerCAmelCase ( *snake_case : Dict ,**snake_case : str ): pass def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. _lowerCamelCase =( "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png" ) @is_pipeline_test @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _lowerCAmelCase ( self : Any ,snake_case : Dict ,snake_case : List[Any] ,snake_case : str ): SCREAMING_SNAKE_CASE =pipeline( 'document-question-answering' ,model=snake_case ,tokenizer=snake_case ,image_processor=snake_case ) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE =list(zip(*apply_tesseract(load_image(snake_case ) ,snake_case ,'' ) ) ) SCREAMING_SNAKE_CASE ='What is the placebo?' SCREAMING_SNAKE_CASE =[ { 'image': load_image(snake_case ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ,snake_case : int ): SCREAMING_SNAKE_CASE =dqa_pipeline(snake_case ,top_k=2 ) self.assertEqual( snake_case ,[ [ {'score': ANY(snake_case ), 'answer': ANY(snake_case ), 'start': ANY(snake_case ), 'end': ANY(snake_case )}, {'score': ANY(snake_case ), 'answer': ANY(snake_case ), 'start': ANY(snake_case ), 'end': ANY(snake_case )}, ] ] * 3 ,) @require_torch @require_detectrona @require_pytesseract def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pipeline('document-question-answering' ,model='hf-internal-testing/tiny-random-layoutlmv2' ) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE ='How many cats are there?' SCREAMING_SNAKE_CASE =[ {'score': 0.0_001, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39}, {'score': 0.0_001, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40}, ] SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual(nested_simplify(snake_case ,decimals=4 ) ,snake_case ) SCREAMING_SNAKE_CASE =dqa_pipeline({'image': image, 'question': question} ,top_k=2 ) self.assertEqual(nested_simplify(snake_case ,decimals=4 ) ,snake_case ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably SCREAMING_SNAKE_CASE ='./tests/fixtures/tests_samples/COCO/000000039769.png' SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual(snake_case ,[] ) # We can optionnally pass directly the words and bounding boxes SCREAMING_SNAKE_CASE ='./tests/fixtures/tests_samples/COCO/000000039769.png' SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,words=snake_case ,boxes=snake_case ,top_k=2 ) self.assertEqual(snake_case ,[] ) @slow @require_torch @require_detectrona @require_pytesseract def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pipeline( 'document-question-answering' ,model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' ,revision='9977165' ,) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE ='What is the invoice number?' SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.9_944, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_009, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline({'image': image, 'question': question} ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.9_944, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_009, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ [ {'score': 0.9_944, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_009, 'answer': 'us-001', 'start': 16, 'end': 16}, ], ] * 2 ,) @slow @require_torch @require_detectrona @require_pytesseract def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =pipeline( 'document-question-answering' ,model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' ,revision='9977165' ,max_seq_len=50 ,) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE ='What is the invoice number?' SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.9_974, 'answer': '1110212019', 'start': 23, 'end': 23}, {'score': 0.9_948, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline({'image': image, 'question': question} ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.9_974, 'answer': '1110212019', 'start': 23, 'end': 23}, {'score': 0.9_948, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ [ {'score': 0.9_974, 'answer': '1110212019', 'start': 23, 'end': 23}, {'score': 0.9_948, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ] * 2 ,) @slow @require_torch @require_pytesseract @require_vision def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' ,revision='3dc6de3' ,add_prefix_space=snake_case ) SCREAMING_SNAKE_CASE =pipeline( 'document-question-answering' ,model='impira/layoutlm-document-qa' ,tokenizer=snake_case ,revision='3dc6de3' ,) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE ='What is the invoice number?' SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline({'image': image, 'question': question} ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ [ {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23}, ] ] * 2 ,) SCREAMING_SNAKE_CASE =list(zip(*apply_tesseract(load_image(snake_case ) ,snake_case ,'' ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE =dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23}, ] ,) @slow @require_torch @require_pytesseract @require_vision def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' ,revision='3dc6de3' ,add_prefix_space=snake_case ) SCREAMING_SNAKE_CASE =pipeline( 'document-question-answering' ,model='impira/layoutlm-document-qa' ,tokenizer=snake_case ,revision='3dc6de3' ,max_seq_len=50 ,) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE ='What is the invoice number?' SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.9_999, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.9_998, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ,) SCREAMING_SNAKE_CASE =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ [ {'score': 0.9_999, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.9_998, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ] * 2 ,) SCREAMING_SNAKE_CASE =list(zip(*apply_tesseract(load_image(snake_case ) ,snake_case ,'' ) ) ) # This model should also work if `image` is set to None SCREAMING_SNAKE_CASE =dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} ,top_k=2 ) self.assertEqual( nested_simplify(snake_case ,decimals=4 ) ,[ {'score': 0.9_999, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.9_998, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ,) @slow @require_torch def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pipeline( 'document-question-answering' ,model='naver-clova-ix/donut-base-finetuned-docvqa' ,tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' ) ,feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa' ,) SCREAMING_SNAKE_CASE =INVOICE_URL SCREAMING_SNAKE_CASE ='What is the invoice number?' SCREAMING_SNAKE_CASE =dqa_pipeline(image=snake_case ,question=snake_case ,top_k=2 ) self.assertEqual(nested_simplify(snake_case ,decimals=4 ) ,[{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
# limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : str ,snake_case : Union[str, Any] ): super().__init__() self.register_modules(unet=snake_case ,scheduler=snake_case ) @torch.no_grad() def __call__( self : List[Any] ,snake_case : int = 1 ,snake_case : Optional[torch.Generator] = None ,snake_case : int = 50 ,snake_case : Optional[str] = "pil" ,snake_case : bool = True ,**snake_case : Tuple ,): SCREAMING_SNAKE_CASE =torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) ,generator=snake_case ,) SCREAMING_SNAKE_CASE =image.to(self.device ) # set step values self.scheduler.set_timesteps(snake_case ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output SCREAMING_SNAKE_CASE =self.unet(snake_case ,snake_case ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 SCREAMING_SNAKE_CASE =self.scheduler.step(snake_case ,snake_case ,snake_case ).prev_sample SCREAMING_SNAKE_CASE =(image / 2 + 0.5).clamp(0 ,1 ) SCREAMING_SNAKE_CASE =image.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE =self.numpy_to_pil(snake_case ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=snake_case ), "This is a local test"
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
from __future__ import annotations from collections.abc import Sequence from typing import Literal def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count += 1 SCREAMING_SNAKE_CASE ='_' if count > 1: return False else: return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] while True: SCREAMING_SNAKE_CASE =['$'] * len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =[] for i in range(len(lowerCAmelCase_ ) ): for j in range(i + 1, len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =compare_string(binary[i], binary[j] ) if k is False: SCREAMING_SNAKE_CASE ='*' SCREAMING_SNAKE_CASE ='*' temp.append('X' ) for i in range(len(lowerCAmelCase_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(lowerCAmelCase_ ) == 0: return pi SCREAMING_SNAKE_CASE =list(set(lowerCAmelCase_ ) ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for minterm in minterms: SCREAMING_SNAKE_CASE ='' for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =str(minterm % 2 ) + string minterm //= 2 temp.append(lowerCAmelCase_ ) return temp def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[0] * len(lowerCAmelCase_ ) for i in range(len(chart[0] ) ): SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =-1 for j in range(len(lowerCAmelCase_ ) ): if chart[j][i] == 1: count += 1 SCREAMING_SNAKE_CASE =j if count == 1: SCREAMING_SNAKE_CASE =1 for i in range(len(lowerCAmelCase_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =0 temp.append(prime_implicants[i] ) while True: SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =-1 SCREAMING_SNAKE_CASE =0 for i in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =chart[i].count(1 ) if count_n > max_n: SCREAMING_SNAKE_CASE =count_n SCREAMING_SNAKE_CASE =i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =0 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[[0 for x in range(len(lowerCAmelCase_ ) )] for x in range(len(lowerCAmelCase_ ) )] for i in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =prime_implicants[i].count('_' ) for j in range(len(lowerCAmelCase_ ) ): if is_for_table(prime_implicants[i], binary[j], lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =1 return chart def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =int(input('Enter the no. of variables\n' ) ) SCREAMING_SNAKE_CASE =[ float(lowerCAmelCase_ ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] SCREAMING_SNAKE_CASE =decimal_to_binary(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =check(lowerCAmelCase_ ) print('Prime Implicants are:' ) print(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =prime_implicant_chart(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =selection(lowerCAmelCase_, lowerCAmelCase_ ) print('Essential Prime Implicants are:' ) print(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
334
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_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =seq_length SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_input_mask SCREAMING_SNAKE_CASE =use_token_type_ids SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_choices SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Optional[int] ): 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 _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=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 _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase ={"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure)
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _lowerCamelCase ={ "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _lowerCamelCase ={ "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _lowerCamelCase ={ "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } _lowerCamelCase ={ "facebook/dpr-ctx_encoder-single-nq-base": 5_12, "facebook/dpr-ctx_encoder-multiset-base": 5_12, } _lowerCamelCase ={ "facebook/dpr-question_encoder-single-nq-base": 5_12, "facebook/dpr-question_encoder-multiset-base": 5_12, } _lowerCamelCase ={ "facebook/dpr-reader-single-nq-base": 5_12, "facebook/dpr-reader-multiset-base": 5_12, } _lowerCamelCase ={ "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _lowerCamelCase ={ "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _lowerCamelCase ={ "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = DPRContextEncoderTokenizer class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = DPRQuestionEncoderTokenizer _lowerCamelCase =collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) _lowerCamelCase =collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) _lowerCamelCase =R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(lowerCamelCase_ ) class a_ : """simple docstring""" def __call__( self : Any ,snake_case : str ,snake_case : Optional[str] = None ,snake_case : Optional[str] = None ,snake_case : Union[bool, str] = False ,snake_case : Union[bool, str] = False ,snake_case : Optional[int] = None ,snake_case : Optional[Union[str, TensorType]] = None ,snake_case : Optional[bool] = None ,**snake_case : int ,): if titles is None and texts is None: return super().__call__( snake_case ,padding=snake_case ,truncation=snake_case ,max_length=snake_case ,return_tensors=snake_case ,return_attention_mask=snake_case ,**snake_case ,) elif titles is None or texts is None: SCREAMING_SNAKE_CASE =titles if texts is None else texts return super().__call__( snake_case ,snake_case ,padding=snake_case ,truncation=snake_case ,max_length=snake_case ,return_tensors=snake_case ,return_attention_mask=snake_case ,**snake_case ,) SCREAMING_SNAKE_CASE =titles if not isinstance(snake_case ,snake_case ) else [titles] SCREAMING_SNAKE_CASE =texts if not isinstance(snake_case ,snake_case ) else [texts] SCREAMING_SNAKE_CASE =len(snake_case ) SCREAMING_SNAKE_CASE =questions if not isinstance(snake_case ,snake_case ) else [questions] * n_passages assert len(snake_case ) == len( snake_case ), f'There should be as many titles than texts but got {len(snake_case )} titles and {len(snake_case )} texts.' SCREAMING_SNAKE_CASE =super().__call__(snake_case ,snake_case ,padding=snake_case ,truncation=snake_case )['input_ids'] SCREAMING_SNAKE_CASE =super().__call__(snake_case ,add_special_tokens=snake_case ,padding=snake_case ,truncation=snake_case )['input_ids'] SCREAMING_SNAKE_CASE ={ 'input_ids': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(snake_case ,snake_case ) ] } if return_attention_mask is not False: SCREAMING_SNAKE_CASE =[] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) SCREAMING_SNAKE_CASE =attention_mask return self.pad(snake_case ,padding=snake_case ,max_length=snake_case ,return_tensors=snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : BatchEncoding ,snake_case : DPRReaderOutput ,snake_case : int = 16 ,snake_case : int = 64 ,snake_case : int = 4 ,): SCREAMING_SNAKE_CASE =reader_input['input_ids'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =reader_output[:3] SCREAMING_SNAKE_CASE =len(snake_case ) SCREAMING_SNAKE_CASE =sorted(range(snake_case ) ,reverse=snake_case ,key=relevance_logits.__getitem__ ) SCREAMING_SNAKE_CASE =[] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE =list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE =sequence_ids.index(self.sep_token_id ,2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE =sequence_ids.index(self.pad_token_id ) else: SCREAMING_SNAKE_CASE =len(snake_case ) SCREAMING_SNAKE_CASE =self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] ,end_logits=end_logits[doc_id][passage_offset:sequence_len] ,max_answer_length=snake_case ,top_spans=snake_case ,) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] ,relevance_score=relevance_logits[doc_id] ,doc_id=snake_case ,start_index=snake_case ,end_index=snake_case ,text=self.decode(sequence_ids[start_index : end_index + 1] ) ,) ) if len(snake_case ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _lowerCAmelCase ( self : Optional[int] ,snake_case : List[int] ,snake_case : List[int] ,snake_case : int ,snake_case : int ,): SCREAMING_SNAKE_CASE =[] for start_index, start_score in enumerate(snake_case ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) SCREAMING_SNAKE_CASE =sorted(snake_case ,key=lambda snake_case : x[1] ,reverse=snake_case ) SCREAMING_SNAKE_CASE =[] for (start_index, end_index), score in scores: assert start_index <= end_index, f'Wrong span indices: [{start_index}:{end_index}]' SCREAMING_SNAKE_CASE =end_index - start_index + 1 assert length <= max_answer_length, f'Span is too long: {length} > {max_answer_length}' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(snake_case ) == top_spans: break return chosen_span_intervals @add_end_docstrings(lowerCamelCase_ ) class a_ ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase = ['input_ids', 'attention_mask'] __UpperCAmelCase = DPRReaderTokenizer
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
def snake_case__ ( lowerCAmelCase_ = 1000 ): """simple docstring""" SCREAMING_SNAKE_CASE =-1 SCREAMING_SNAKE_CASE =0 for a in range(1, n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c SCREAMING_SNAKE_CASE =(n * n - 2 * a * n) // (2 * n - 2 * a) SCREAMING_SNAKE_CASE =n - a - b if c * c == (a * a + b * b): SCREAMING_SNAKE_CASE =a * b * c if candidate >= product: SCREAMING_SNAKE_CASE =candidate return product if __name__ == "__main__": print(f'{solution() = }')
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
class a_ : """simple docstring""" def __init__( self : Union[str, Any] ,snake_case : list ): SCREAMING_SNAKE_CASE =set_counts SCREAMING_SNAKE_CASE =max(snake_case ) SCREAMING_SNAKE_CASE =len(snake_case ) SCREAMING_SNAKE_CASE =[1] * num_sets SCREAMING_SNAKE_CASE =list(range(snake_case ) ) def _lowerCAmelCase ( self : int ,snake_case : int ,snake_case : int ): SCREAMING_SNAKE_CASE =self.get_parent(snake_case ) SCREAMING_SNAKE_CASE =self.get_parent(snake_case ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 SCREAMING_SNAKE_CASE =self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =src_parent SCREAMING_SNAKE_CASE =self.set_counts[src_parent] SCREAMING_SNAKE_CASE =max(self.max_set ,snake_case ) return True def _lowerCAmelCase ( self : Optional[int] ,snake_case : int ): if self.parents[disj_set] == disj_set: return disj_set SCREAMING_SNAKE_CASE =self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "microsoft/table-transformer-detection": ( "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json" ), } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'table-transformer' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=True ,snake_case : Dict=None ,snake_case : Union[str, Any]=3 ,snake_case : Optional[int]=100 ,snake_case : List[Any]=6 ,snake_case : Dict=2048 ,snake_case : int=8 ,snake_case : Tuple=6 ,snake_case : Union[str, Any]=2048 ,snake_case : Union[str, Any]=8 ,snake_case : int=0.0 ,snake_case : Dict=0.0 ,snake_case : Tuple=True ,snake_case : int="relu" ,snake_case : Any=256 ,snake_case : Tuple=0.1 ,snake_case : int=0.0 ,snake_case : List[str]=0.0 ,snake_case : str=0.02 ,snake_case : List[str]=1.0 ,snake_case : Any=False ,snake_case : Tuple="sine" ,snake_case : int="resnet50" ,snake_case : Optional[int]=True ,snake_case : Optional[Any]=False ,snake_case : str=1 ,snake_case : List[Any]=5 ,snake_case : Optional[Any]=2 ,snake_case : int=1 ,snake_case : List[str]=1 ,snake_case : Union[str, Any]=5 ,snake_case : str=2 ,snake_case : int=0.1 ,**snake_case : Dict ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =backbone_config.get('model_type' ) SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE =config_class.from_dict(snake_case ) # set timm attributes to None SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =None, None, None SCREAMING_SNAKE_CASE =use_timm_backbone SCREAMING_SNAKE_CASE =backbone_config SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =num_queries SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =init_xavier_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =auxiliary_loss SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =backbone SCREAMING_SNAKE_CASE =use_pretrained_backbone SCREAMING_SNAKE_CASE =dilation # Hungarian matcher SCREAMING_SNAKE_CASE =class_cost SCREAMING_SNAKE_CASE =bbox_cost SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients SCREAMING_SNAKE_CASE =mask_loss_coefficient SCREAMING_SNAKE_CASE =dice_loss_coefficient SCREAMING_SNAKE_CASE =bbox_loss_coefficient SCREAMING_SNAKE_CASE =giou_loss_coefficient SCREAMING_SNAKE_CASE =eos_coefficient super().__init__(is_encoder_decoder=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : int ): return self.encoder_attention_heads @property def _lowerCAmelCase ( self : Any ): return self.d_model class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = version.parse('1.11' ) @property def _lowerCAmelCase ( self : Dict ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def _lowerCAmelCase ( self : Union[str, Any] ): return 1e-5 @property def _lowerCAmelCase ( self : Union[str, Any] ): return 12
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase_ ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = field(default='summarization' , metadata={'include_in_asdict_even_if_is_default': True} ) __UpperCAmelCase = Features({'text': Value('string' )} ) __UpperCAmelCase = Features({'summary': Value('string' )} ) __UpperCAmelCase = "text" __UpperCAmelCase = "summary" @property def _lowerCAmelCase ( self : Any ): return {self.text_column: "text", self.summary_column: "summary"}
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = ['input_features', 'attention_mask'] def __init__( self : List[str] ,snake_case : Any=80 ,snake_case : Optional[Any]=16000 ,snake_case : str=80 ,snake_case : Tuple=0.0 ,snake_case : List[Any]=True ,snake_case : str=True ,snake_case : Optional[int]=True ,**snake_case : Optional[Any] ,): super().__init__(feature_size=snake_case ,sampling_rate=snake_case ,padding_value=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =num_mel_bins SCREAMING_SNAKE_CASE =do_ceptral_normalize SCREAMING_SNAKE_CASE =normalize_means SCREAMING_SNAKE_CASE =normalize_vars SCREAMING_SNAKE_CASE =True def _lowerCAmelCase ( self : Dict ,snake_case : np.ndarray ,): SCREAMING_SNAKE_CASE =waveform * (2**15) # Kaldi compliance: 16-bit signed integers SCREAMING_SNAKE_CASE =torch.from_numpy(snake_case ).unsqueeze(0 ) SCREAMING_SNAKE_CASE =ta_kaldi.fbank(snake_case ,num_mel_bins=self.num_mel_bins ,sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _lowerCAmelCase ( snake_case : np.ndarray ,snake_case : int ,snake_case : Optional[bool] = True ,snake_case : Optional[bool] = True ,snake_case : float = 0.0 ,): # make sure we normalize float32 arrays if normalize_means: SCREAMING_SNAKE_CASE =x[:input_length].mean(axis=0 ) SCREAMING_SNAKE_CASE =np.subtract(snake_case ,snake_case ) if normalize_vars: SCREAMING_SNAKE_CASE =x[:input_length].std(axis=0 ) SCREAMING_SNAKE_CASE =np.divide(snake_case ,snake_case ) if input_length < x.shape[0]: SCREAMING_SNAKE_CASE =padding_value # make sure array is in float32 SCREAMING_SNAKE_CASE =x.astype(np.floataa ) return x def _lowerCAmelCase ( self : List[Any] ,snake_case : List[np.ndarray] ,snake_case : Optional[np.ndarray] = None ): SCREAMING_SNAKE_CASE =attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(snake_case ,snake_case ,self.normalize_means ,self.normalize_vars ,self.padding_value ) for x, n in zip(snake_case ,snake_case ) ] def __call__( self : str ,snake_case : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,snake_case : Union[bool, str, PaddingStrategy] = False ,snake_case : Optional[int] = None ,snake_case : bool = False ,snake_case : Optional[int] = None ,snake_case : Optional[Union[str, TensorType]] = None ,snake_case : Optional[int] = None ,snake_case : Optional[bool] = None ,**snake_case : Optional[Any] ,): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) SCREAMING_SNAKE_CASE =isinstance(snake_case ,np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) SCREAMING_SNAKE_CASE =is_batched_numpy or ( isinstance(snake_case ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE =[np.asarray(snake_case ,dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(snake_case ,np.ndarray ): SCREAMING_SNAKE_CASE =np.asarray(snake_case ,dtype=np.floataa ) elif isinstance(snake_case ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE =raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE =[raw_speech] # extract fbank features SCREAMING_SNAKE_CASE =[self._extract_fbank_features(snake_case ) for waveform in raw_speech] # convert into correct format for padding SCREAMING_SNAKE_CASE =BatchFeature({'input_features': features} ) SCREAMING_SNAKE_CASE =self.pad( snake_case ,padding=snake_case ,max_length=snake_case ,truncation=snake_case ,pad_to_multiple_of=snake_case ,return_attention_mask=snake_case ,**snake_case ,) # make sure list is in array format SCREAMING_SNAKE_CASE =padded_inputs.get('input_features' ) if isinstance(input_features[0] ,snake_case ): SCREAMING_SNAKE_CASE =[np.asarray(snake_case ,dtype=np.floataa ) for feature in input_features] SCREAMING_SNAKE_CASE =padded_inputs.get('attention_mask' ) if attention_mask is not None: SCREAMING_SNAKE_CASE =[np.asarray(snake_case ,dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: SCREAMING_SNAKE_CASE =( np.array(snake_case ,dtype=np.intaa ) if self._get_padding_strategies(snake_case ,max_length=snake_case ) is not PaddingStrategy.DO_NOT_PAD else None ) SCREAMING_SNAKE_CASE =self.normalize( padded_inputs['input_features'] ,attention_mask=snake_case ) if return_tensors is not None: SCREAMING_SNAKE_CASE =padded_inputs.convert_to_tensors(snake_case ) return padded_inputs
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
import fire from utils import calculate_rouge, save_json def _a ( a :Optional[int] , a :Tuple , a :Tuple=None , **a :Union[str, Any] ) -> Any: a = [x.strip() for x in open(a ).readlines()] a = [x.strip() for x in open(a ).readlines()][: len(a )] a = calculate_rouge(a , a , **a ) if save_path is not None: save_json(a , a , indent=a ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
0
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,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 ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =config_and_inputs SCREAMING_SNAKE_CASE ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(snake_case ) SCREAMING_SNAKE_CASE =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] SCREAMING_SNAKE_CASE =['pixel_values'] self.assertListEqual(arg_names[:1] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
0
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> str: '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> Dict: '''simple docstring''' UpperCAmelCase_ = np.max(_outputs , axis=-1 , keepdims=snake_case_ ) UpperCAmelCase_ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=snake_case_ ) class __A ( UpperCamelCase__ ): a__ : List[str] = """sigmoid""" a__ : Tuple = """softmax""" a__ : Union[str, Any] = """none""" @add_end_docstrings( UpperCamelCase__ , r""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class __A ( UpperCamelCase__ ): a__ : Optional[Any] = False a__ : List[str] = ClassificationFunction.NONE def __init__(self : Dict , **__a : Any ): super().__init__(**__a ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def _lowercase (self : Dict , __a : Dict=None , __a : Any=None , __a : int="" , **__a : Dict ): # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" UpperCAmelCase_ = tokenizer_kwargs UpperCAmelCase_ = {} if hasattr(self.model.config , "return_all_scores" ) and return_all_scores is None: UpperCAmelCase_ = self.model.config.return_all_scores if isinstance(__a , __a ) or top_k is None: UpperCAmelCase_ = top_k UpperCAmelCase_ = False elif return_all_scores is not None: warnings.warn( "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`." , __a , ) if return_all_scores: UpperCAmelCase_ = None else: UpperCAmelCase_ = 1 if isinstance(__a , __a ): UpperCAmelCase_ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: UpperCAmelCase_ = function_to_apply return preprocess_params, {}, postprocess_params def __call__(self : Optional[int] , *__a : List[Any] , **__a : Tuple ): UpperCAmelCase_ = super().__call__(*__a , **__a ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. UpperCAmelCase_ = "top_k" not in kwargs if isinstance(args[0] , __a ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def _lowercase (self : Optional[Any] , __a : Dict , **__a : List[str] ): UpperCAmelCase_ = self.framework if isinstance(__a , __a ): return self.tokenizer(**__a , return_tensors=__a , **__a ) elif isinstance(__a , __a ) and len(__a ) == 1 and isinstance(inputs[0] , __a ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__a , **__a ) elif isinstance(__a , __a ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair." ) return self.tokenizer(__a , return_tensors=__a , **__a ) def _lowercase (self : Dict , __a : Optional[Any] ): return self.model(**__a ) def _lowercase (self : Dict , __a : int , __a : int=None , __a : List[str]=1 , __a : List[str]=True ): # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: UpperCAmelCase_ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: UpperCAmelCase_ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , "function_to_apply" ) and function_to_apply is None: UpperCAmelCase_ = self.model.config.function_to_apply else: UpperCAmelCase_ = ClassificationFunction.NONE UpperCAmelCase_ = model_outputs["logits"][0] UpperCAmelCase_ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: UpperCAmelCase_ = sigmoid(__a ) elif function_to_apply == ClassificationFunction.SOFTMAX: UpperCAmelCase_ = softmax(__a ) elif function_to_apply == ClassificationFunction.NONE: UpperCAmelCase_ = outputs else: raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} UpperCAmelCase_ = [ {"label": self.model.config.idalabel[i], "score": score.item()} for i, score in enumerate(__a ) ] if not _legacy: dict_scores.sort(key=lambda __a : x["score"] , reverse=__a ) if top_k is not None: UpperCAmelCase_ = dict_scores[:top_k] return dict_scores
1
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser lowerCamelCase : Dict = logging.getLogger(__name__) torch.set_grad_enabled(False) lowerCamelCase : List[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def _SCREAMING_SNAKE_CASE (A , A=100 , A=" " ) -> List[str]: """simple docstring""" lowercase__ = text.split(A ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(A ) , A )] def _SCREAMING_SNAKE_CASE (A ) -> dict: """simple docstring""" lowercase__ ,lowercase__ = [], [] for title, text in zip(documents['''title'''] , documents['''text'''] ): if text is not None: for passage in split_text(A ): titles.append(title if title is not None else '''''' ) texts.append(A ) return {"title": titles, "text": texts} def _SCREAMING_SNAKE_CASE (A , A , A ) -> dict: """simple docstring""" lowercase__ = ctx_tokenizer( documents['''title'''] , documents['''text'''] , truncation=A , padding='''longest''' , return_tensors='''pt''' )['''input_ids'''] lowercase__ = ctx_encoder(input_ids.to(device=A ) , return_dict=A ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def _SCREAMING_SNAKE_CASE (A , A , A , ) -> List[str]: """simple docstring""" logger.info('''Step 1 - Create the dataset''' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way lowercase__ = load_dataset( '''csv''' , data_files=[rag_example_args.csv_path] , split='''train''' , delimiter='''\t''' , column_names=['''title''', '''text'''] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words lowercase__ = dataset.map(A , batched=A , num_proc=processing_args.num_proc ) # And compute the embeddings lowercase__ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=A ) lowercase__ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) lowercase__ = Features( {'''text''': Value('''string''' ), '''title''': Value('''string''' ), '''embeddings''': Sequence(Value('''float32''' ) )} ) # optional, save as float32 instead of float64 to save space lowercase__ = dataset.map( partial(A , ctx_encoder=A , ctx_tokenizer=A ) , batched=A , batch_size=processing_args.batch_size , features=A , ) # And finally save your dataset lowercase__ = os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset''' ) dataset.save_to_disk(A ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('''Step 2 - Index the dataset''' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search lowercase__ = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('''embeddings''' , custom_index=A ) # And save the index lowercase__ = os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset_hnsw_index.faiss''' ) dataset.get_index('''embeddings''' ).save(A ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : str = field( default=str(Path(lowercase_ ).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv""" ) , metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""} , ) lowerCAmelCase__ : Optional[str] = field( default=lowercase_ , metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""} , ) lowerCAmelCase__ : str = field( default="""facebook/rag-sequence-nq""" , metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""} , ) lowerCAmelCase__ : str = field( default="""facebook/dpr-ctx_encoder-multiset-base""" , metadata={ """help""": ( """The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or""" """ 'facebook/dpr-ctx_encoder-multiset-base'""" ) } , ) lowerCAmelCase__ : Optional[str] = field( default=str(Path(lowercase_ ).parent / """test_run""" / """dummy-kb""" ) , metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""} , ) @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : Optional[int] = field( default=lowercase_ , metadata={ """help""": """The number of processes to use to split the documents into passages. Default is single process.""" } , ) lowerCAmelCase__ : int = field( default=16 , metadata={ """help""": """The batch size to use when computing the passages embeddings using the DPR context encoder.""" } , ) @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : int = field( default=768 , metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""} , ) lowerCAmelCase__ : int = field( default=128 , metadata={ """help""": ( """The number of bi-directional links created for every new element during the HNSW index construction.""" ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) lowerCamelCase : Optional[Any] = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) lowerCamelCase , lowerCamelCase , lowerCamelCase : Union[str, Any] = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: lowerCamelCase : Optional[int] = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
2
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = 16 ): """simple docstring""" SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('bert-base-cased' ) SCREAMING_SNAKE_CASE =load_dataset('glue', 'mrpc' ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowerCAmelCase_, max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE =datasets.map( lowerCAmelCase_, batched=lowerCAmelCase_, remove_columns=['idx', 'sentence1', 'sentence2'], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE =16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE =8 else: SCREAMING_SNAKE_CASE =None return tokenizer.pad( lowerCAmelCase_, padding='longest', max_length=lowerCAmelCase_, pad_to_multiple_of=lowerCAmelCase_, return_tensors='pt', ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['train'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =DataLoader( tokenized_datasets['validation'], shuffle=lowerCAmelCase_, collate_fn=lowerCAmelCase_, batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if os.environ.get('TESTING_MOCKED_DATALOADERS', lowerCAmelCase_ ) == "1": SCREAMING_SNAKE_CASE =2 # Initialize accelerator SCREAMING_SNAKE_CASE =Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE =config['lr'] SCREAMING_SNAKE_CASE =int(config['num_epochs'] ) SCREAMING_SNAKE_CASE =int(config['seed'] ) SCREAMING_SNAKE_CASE =int(config['batch_size'] ) SCREAMING_SNAKE_CASE =evaluate.load('glue', 'mrpc' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE =AutoModelForSequenceClassification.from_pretrained('bert-base-cased', return_dict=lowerCAmelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE =model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE =AdamW(params=model.parameters(), lr=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =get_dataloaders(lowerCAmelCase_, lowerCAmelCase_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE =get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_, num_warmup_steps=100, num_training_steps=(len(lowerCAmelCase_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.prepare( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCAmelCase_, references=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:', lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision', type=lowerCAmelCase_, default=lowerCAmelCase_, choices=['no', 'fp16', 'bf16', 'fp8'], help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.', ) parser.add_argument('--cpu', action='store_true', help='If passed, will train on the CPU.' ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE ={'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCAmelCase_, lowerCAmelCase_ ) if __name__ == "__main__": main()
334
0
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Tuple = logging.get_logger(__name__) lowercase : Union[str, Any] = { 'huggingface/informer-tourism-monthly': ( 'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json' ), # See all Informer models at https://huggingface.co/models?filter=informer } class A ( __snake_case ): __magic_name__ = '''informer''' __magic_name__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "student_t" , SCREAMING_SNAKE_CASE = "nll" , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "mean" , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = 0 , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 64 , SCREAMING_SNAKE_CASE = 32 , SCREAMING_SNAKE_CASE = 32 , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = 2 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = "gelu" , SCREAMING_SNAKE_CASE = 0.05 , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 100 , SCREAMING_SNAKE_CASE = 0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE = "prob" , SCREAMING_SNAKE_CASE = 5 , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" A : Any = prediction_length A : Dict = context_length or prediction_length A : List[Any] = distribution_output A : List[str] = loss A : int = input_size A : List[Any] = num_time_features A : str = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] A : List[str] = scaling A : Any = num_dynamic_real_features A : str = num_static_real_features A : Optional[int] = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) A : str = cardinality else: A : List[Any] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) A : int = embedding_dimension else: A : List[str] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] A : int = num_parallel_samples # Transformer architecture configuration A : str = input_size * len(self.lags_sequence ) + self._number_of_features A : Dict = d_model A : int = encoder_attention_heads A : Optional[Any] = decoder_attention_heads A : Union[str, Any] = encoder_ffn_dim A : int = decoder_ffn_dim A : Tuple = encoder_layers A : List[str] = decoder_layers A : Optional[int] = dropout A : List[Any] = attention_dropout A : List[Any] = activation_dropout A : int = encoder_layerdrop A : str = decoder_layerdrop A : Optional[Any] = activation_function A : List[str] = init_std A : List[str] = use_cache # Informer A : List[Any] = attention_type A : Tuple = sampling_factor A : Dict = distil super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @property def __lowerCAmelCase ( self ) -> int: """simple docstring""" return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
3
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
0
'''simple docstring''' import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __snake_case =logging.get_logger(__name__) class UpperCAmelCase_ ( enum.Enum ): lowerCamelCase : Optional[int] = 0 lowerCamelCase : str = 1 @add_end_docstrings(__lowercase ) class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Tuple = '''generated''' def __init__( self : Optional[int] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def __UpperCAmelCase ( self : Dict , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : List[str] , ) -> Union[str, Any]: lowerCAmelCase = {} if truncation is not None: lowerCAmelCase = truncation lowerCAmelCase = generate_kwargs lowerCAmelCase = {} if return_tensors is not None and return_type is None: lowerCAmelCase = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: lowerCAmelCase = return_type if clean_up_tokenization_spaces is not None: lowerCAmelCase = clean_up_tokenization_spaces if stop_sequence is not None: lowerCAmelCase = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( 'Stopping on a multiple token sequence is not yet supported on transformers. The first token of' ' the stop sequence will be used as the stop sequence string in the interim.' ) lowerCAmelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __UpperCAmelCase ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[Any]: return True def __UpperCAmelCase ( self : Optional[int] , *UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: lowerCAmelCase = self.model.config.prefix if self.model.config.prefix is not None else '' if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input' ) lowerCAmelCase = ([prefix + arg for arg in args[0]],) lowerCAmelCase = True elif isinstance(args[0] , UpperCAmelCase__ ): lowerCAmelCase = (prefix + args[0],) lowerCAmelCase = False else: raise ValueError( F''' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`''' ) lowerCAmelCase = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : Optional[Any] , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : str ) -> List[Any]: lowerCAmelCase = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> int: lowerCAmelCase = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def __UpperCAmelCase ( self : int , UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : str ) -> Tuple: if self.framework == "pt": lowerCAmelCase , lowerCAmelCase = model_inputs['input_ids'].shape elif self.framework == "tf": lowerCAmelCase , lowerCAmelCase = tf.shape(model_inputs['input_ids'] ).numpy() lowerCAmelCase = generate_kwargs.get('min_length' , self.model.config.min_length ) lowerCAmelCase = generate_kwargs.get('max_length' , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs['min_length'] , generate_kwargs['max_length'] ) lowerCAmelCase = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) lowerCAmelCase = output_ids.shape[0] if self.framework == "pt": lowerCAmelCase = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": lowerCAmelCase = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def __UpperCAmelCase ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any]=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> int: lowerCAmelCase = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: lowerCAmelCase = {F'''{self.return_name}_token_ids''': output_ids} elif return_type == ReturnType.TEXT: lowerCAmelCase = { F'''{self.return_name}_text''': self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(__lowercase ) class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Union[str, Any] = '''summary''' def __call__( self : Any , *UpperCAmelCase__ : int , **UpperCAmelCase__ : str ) -> Union[str, Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F'''Your min_length={min_length} must be inferior than your max_length={max_length}.''' ) if input_length < max_length: logger.warning( F'''Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is ''' 'a summarization task, where outputs shorter than the input are typically wanted, you might ' F'''consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})''' ) @add_end_docstrings(__lowercase ) class UpperCAmelCase_ ( __lowercase ): lowerCamelCase : Union[str, Any] = '''translation''' def __UpperCAmelCase ( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: if input_length > 0.9 * max_length: logger.warning( F'''Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider ''' 'increasing your max_length manually, e.g. translator(\'...\', max_length=400)' ) return True def __UpperCAmelCase ( self : Union[str, Any] , *UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Optional[int]=None ) -> str: if getattr(self.tokenizer , '_build_translation_inputs' , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : int ) -> Tuple: lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: lowerCAmelCase = src_lang if tgt_lang is not None: lowerCAmelCase = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. lowerCAmelCase = kwargs.get('task' , self.task ) lowerCAmelCase = task.split('_' ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY lowerCAmelCase = items[1] lowerCAmelCase = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : Optional[int] , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
4
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
0
import os # Precomputes a list of the 100 first triangular numbers UpperCAmelCase__ = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def UpperCAmelCase_ ( ) -> Tuple: """simple docstring""" _lowercase =os.path.dirname(os.path.realpath(__snake_case ) ) _lowercase =os.path.join(__snake_case , '''words.txt''' ) _lowercase ='''''' with open(__snake_case ) as f: _lowercase =f.readline() _lowercase =[word.strip('''"''' ) for word in words.strip('''\r\n''' ).split(''',''' )] _lowercase =[ word for word in [sum(ord(__snake_case ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__snake_case ) if __name__ == "__main__": print(solution())
5
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING A : Optional[int] = logging.get_logger(__name__) A : List[Any] = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class __A( a ): snake_case_ = '''instructblip_vision_model''' def __init__( self , _snake_case=1_408 , _snake_case=6_144 , _snake_case=39 , _snake_case=16 , _snake_case=224 , _snake_case=14 , _snake_case="gelu" , _snake_case=1E-6 , _snake_case=0.0 , _snake_case=1E-10 , _snake_case=True , **_snake_case , ) -> List[str]: '''simple docstring''' super().__init__(**_snake_case ) __a = hidden_size __a = intermediate_size __a = num_hidden_layers __a = num_attention_heads __a = patch_size __a = image_size __a = initializer_range __a = attention_dropout __a = layer_norm_eps __a = hidden_act __a = qkv_bias @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , **_snake_case ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __a , __a = cls.get_config_dict(_snake_case , **_snake_case ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": __a = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(_snake_case , **_snake_case ) class __A( a ): snake_case_ = '''instructblip_qformer''' def __init__( self , _snake_case=30_522 , _snake_case=768 , _snake_case=12 , _snake_case=12 , _snake_case=3_072 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=512 , _snake_case=0.02 , _snake_case=1E-12 , _snake_case=0 , _snake_case="absolute" , _snake_case=2 , _snake_case=1_408 , **_snake_case , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=_snake_case , **_snake_case ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = cross_attention_frequency __a = encoder_hidden_size @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , **_snake_case ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __a , __a = cls.get_config_dict(_snake_case , **_snake_case ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('''model_type''' ) == "instructblip": __a = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(_snake_case , **_snake_case ) class __A( a ): snake_case_ = '''instructblip''' snake_case_ = True def __init__( self , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case=32 , **_snake_case ) -> Optional[Any]: '''simple docstring''' super().__init__(**_snake_case ) if vision_config is None: __a = {} logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.''' ) if qformer_config is None: __a = {} logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.''' ) if text_config is None: __a = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) __a = InstructBlipVisionConfig(**_snake_case ) __a = InstructBlipQFormerConfig(**_snake_case ) __a = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' __a = CONFIG_MAPPING[text_model_type](**_snake_case ) __a = self.text_config.tie_word_embeddings __a = self.text_config.is_encoder_decoder __a = num_query_tokens __a = self.vision_config.hidden_size __a = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __a = 1.0 __a = 0.02 @classmethod def SCREAMING_SNAKE_CASE_ ( cls , _snake_case , _snake_case , _snake_case , **_snake_case , ) -> Optional[int]: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_snake_case , ) def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = copy.deepcopy(self.__dict__ ) __a = self.vision_config.to_dict() __a = self.qformer_config.to_dict() __a = self.text_config.to_dict() __a = self.__class__.model_type return output
6
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
0
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class A : """simple docstring""" lowerCamelCase = 42 lowerCamelCase = field(default_factory=_UpperCAmelCase ) lowerCamelCase = field(default_factory=_UpperCAmelCase ) def snake_case__ ( self : Union[str, Any],lowercase_ : Any,lowercase_ : Tensor,lowercase_ : Tensor )-> List[Any]: '''simple docstring''' A__ = len(list(m.modules() ) ) == 1 or isinstance(lowercase_,nn.Convad ) or isinstance(lowercase_,nn.BatchNormad ) if has_not_submodules: self.traced.append(lowercase_ ) def __call__( self : Dict,lowercase_ : Tensor )-> Tuple: '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(lowercase_ ) [x.remove() for x in self.handles] return self @property def snake_case__ ( self : str )-> Optional[Any]: '''simple docstring''' return list(filter(lambda lowercase_ : len(list(x.state_dict().keys() ) ) > 0,self.traced ) ) @dataclass class A : """simple docstring""" lowerCamelCase = 42 lowerCamelCase = 42 lowerCamelCase = 0 lowerCamelCase = field(default_factory=_UpperCAmelCase ) lowerCamelCase = field(default_factory=_UpperCAmelCase ) def __call__( self : List[str],lowercase_ : Tensor )-> Union[str, Any]: '''simple docstring''' A__ = Tracker(self.dest )(lowercase_ ).parametrized A__ = Tracker(self.src )(lowercase_ ).parametrized A__ = list(filter(lambda lowercase_ : type(lowercase_ ) not in self.src_skip,lowercase_ ) ) A__ = list(filter(lambda lowercase_ : type(lowercase_ ) not in self.dest_skip,lowercase_ ) ) if len(lowercase_ ) != len(lowercase_ ): raise Exception( F'Numbers of operations are different. Source module has {len(lowercase_ )} operations while' F' destination module has {len(lowercase_ )}.' ) for dest_m, src_m in zip(lowercase_,lowercase_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'Transfered from={src_m} to={dest_m}' ) def _snake_case( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : ResNetConfig , SCREAMING_SNAKE_CASE__ : Path , SCREAMING_SNAKE_CASE__ : bool = True ) -> int: '''simple docstring''' print(f'Converting {name}...' ) with torch.no_grad(): A__ = timm.create_model(SCREAMING_SNAKE_CASE__ , pretrained=SCREAMING_SNAKE_CASE__ ).eval() A__ = ResNetForImageClassification(SCREAMING_SNAKE_CASE__ ).eval() A__ = ModuleTransfer(src=SCREAMING_SNAKE_CASE__ , dest=SCREAMING_SNAKE_CASE__ ) A__ = torch.randn((1, 3, 224, 224) ) module_transfer(SCREAMING_SNAKE_CASE__ ) assert torch.allclose(from_model(SCREAMING_SNAKE_CASE__ ) , our_model(SCREAMING_SNAKE_CASE__ ).logits ), "The model logits don't match the original one." A__ = f'resnet{"-".join(name.split("resnet" ) )}' print(SCREAMING_SNAKE_CASE__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='Add model' , use_temp_dir=SCREAMING_SNAKE_CASE__ , ) # we can use the convnext one A__ = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='Add image processor' , use_temp_dir=SCREAMING_SNAKE_CASE__ , ) print(f'Pushed {checkpoint_name}' ) def _snake_case( SCREAMING_SNAKE_CASE__ : Path , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = True ) -> Dict: '''simple docstring''' A__ = 'imagenet-1k-id2label.json' A__ = 1000 A__ = (1, num_labels) A__ = 'huggingface/label-files' A__ = num_labels A__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) ) A__ = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} A__ = idalabel A__ = {v: k for k, v in idalabel.items()} A__ = partial(SCREAMING_SNAKE_CASE__ , num_labels=SCREAMING_SNAKE_CASE__ , idalabel=SCREAMING_SNAKE_CASE__ , labelaid=SCREAMING_SNAKE_CASE__ ) A__ = { 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='bottleneck' ), } if model_name: convert_weight_and_push(SCREAMING_SNAKE_CASE__ , names_to_config[model_name] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
7
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class snake_case_ ( unittest.TestCase ): '''simple docstring''' @slow def snake_case__( self : int ) ->str: snake_case_ = TFCamembertModel.from_pretrained('''jplu/tf-camembert-base''' ) snake_case_ = tf.convert_to_tensor( [[5, 1_2_1, 1_1, 6_6_0, 1_6, 7_3_0, 2_5_5_4_3, 1_1_0, 8_3, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" snake_case_ = model(_UpperCamelCase )['''last_hidden_state'''] snake_case_ = tf.TensorShape((1, 1_0, 7_6_8) ) self.assertEqual(output.shape , _UpperCamelCase ) # compare the actual values for a slice. snake_case_ = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
8
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
0
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract __lowerCAmelCase : int =logging.get_logger(__name__) def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ = None ): __SCREAMING_SNAKE_CASE : int = tesseract_config if tesseract_config is not None else '''''' # apply OCR __SCREAMING_SNAKE_CASE : List[Any] = to_pil_image(lowercase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = pil_image.size __SCREAMING_SNAKE_CASE : Tuple = pytesseract.image_to_data(lowercase__ , lang=lowercase__ , output_type='''dict''' , config=lowercase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates __SCREAMING_SNAKE_CASE : Union[str, Any] = [idx for idx, word in enumerate(lowercase__ ) if not word.strip()] __SCREAMING_SNAKE_CASE : List[str] = [word for idx, word in enumerate(lowercase__ ) if idx not in irrelevant_indices] __SCREAMING_SNAKE_CASE : Dict = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] __SCREAMING_SNAKE_CASE : Union[str, Any] = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] __SCREAMING_SNAKE_CASE : Dict = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] __SCREAMING_SNAKE_CASE : Union[str, Any] = [coord for idx, coord in enumerate(lowercase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format __SCREAMING_SNAKE_CASE : List[Any] = [] for x, y, w, h in zip(lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [x, y, x + w, y + h] actual_boxes.append(lowercase__ ) # finally, normalize the bounding boxes __SCREAMING_SNAKE_CASE : Dict = [] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase__ , lowercase__ , lowercase__ ) ) assert len(lowercase__ ) == len(lowercase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['''pixel_values'''] def __init__( self :Optional[int] , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Dict[str, int] = None , lowerCAmelCase__ :PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Optional[str] = None , lowerCAmelCase__ :Optional[str] = "" , **lowerCAmelCase__ :str , ) -> None: super().__init__(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[str] = size if size is not None else {'''height''': 224, '''width''': 224} __SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = resample __SCREAMING_SNAKE_CASE : int = apply_ocr __SCREAMING_SNAKE_CASE : Tuple = ocr_lang __SCREAMING_SNAKE_CASE : List[Any] = tesseract_config def __magic_name__( self :Optional[int] , lowerCAmelCase__ :np.ndarray , lowerCAmelCase__ :Dict[str, int] , lowerCAmelCase__ :PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase__ :Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase__ :Tuple , ) -> np.ndarray: __SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(lowerCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = (size['''height'''], size['''width''']) return resize(lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :ImageInput , lowerCAmelCase__ :bool = None , lowerCAmelCase__ :Dict[str, int] = None , lowerCAmelCase__ :PILImageResampling = None , lowerCAmelCase__ :bool = None , lowerCAmelCase__ :Optional[str] = None , lowerCAmelCase__ :Optional[str] = None , lowerCAmelCase__ :Optional[Union[str, TensorType]] = None , lowerCAmelCase__ :ChannelDimension = ChannelDimension.FIRST , **lowerCAmelCase__ :Dict , ) -> PIL.Image.Image: __SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else self.size __SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE : List[Any] = apply_ocr if apply_ocr is not None else self.apply_ocr __SCREAMING_SNAKE_CASE : Union[str, Any] = ocr_lang if ocr_lang is not None else self.ocr_lang __SCREAMING_SNAKE_CASE : List[str] = tesseract_config if tesseract_config is not None else self.tesseract_config __SCREAMING_SNAKE_CASE : Any = make_list_of_images(lowerCAmelCase__ ) if not valid_images(lowerCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE : Any = [to_numpy_array(lowerCAmelCase__ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) __SCREAMING_SNAKE_CASE : Tuple = [] __SCREAMING_SNAKE_CASE : Any = [] for image in images: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = apply_tesseract(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) words_batch.append(lowerCAmelCase__ ) boxes_batch.append(lowerCAmelCase__ ) if do_resize: __SCREAMING_SNAKE_CASE : Optional[Any] = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) __SCREAMING_SNAKE_CASE : Any = [flip_channel_order(lowerCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE : List[Any] = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE : Optional[Any] = BatchFeature(data={'''pixel_values''': images} , tensor_type=lowerCAmelCase__ ) if apply_ocr: __SCREAMING_SNAKE_CASE : Any = words_batch __SCREAMING_SNAKE_CASE : Optional[Any] = boxes_batch return data
9
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 a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =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 =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =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(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) 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 , SCREAMING_SNAKE_CASE =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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, 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, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) 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 snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) 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 , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, '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 snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
0
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __A = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __A = "main" # Default branch name __A = "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2" # One particular commit (not the top of `main`) __A = "aaaaaaa" # This commit does not exist, so we should 404. __A = "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684" # Sha-1 of config.json on the top of `main`, for checking purposes __A = "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3" @contextlib.contextmanager def lowerCAmelCase_ ( ) -> List[Any]: """simple docstring""" print("Welcome!" ) yield print("Bye!" ) @contextlib.contextmanager def lowerCAmelCase_ ( ) -> int: """simple docstring""" print("Bonjour!" ) yield print("Au revoir!" ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]: '''simple docstring''' assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers") is not None class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' with ContextManagers([]): print("Transformers are awesome!") # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , "Transformers are awesome!\n") @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[str]) ->Any: '''simple docstring''' with ContextManagers([context_en()]): print("Transformers are awesome!") # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Welcome!\nTransformers are awesome!\nBye!\n") @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : Dict) ->List[Any]: '''simple docstring''' with ContextManagers([context_fr(), context_en()]): print("Transformers are awesome!") # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n") @require_torch def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' self.assertEqual(find_labels(UpperCAmelCase_) , ["labels"]) self.assertEqual(find_labels(UpperCAmelCase_) , ["labels", "next_sentence_label"]) self.assertEqual(find_labels(UpperCAmelCase_) , ["start_positions", "end_positions"]) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' pass self.assertEqual(find_labels(UpperCAmelCase_) , ["labels"]) @require_tf def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[Any]: '''simple docstring''' self.assertEqual(find_labels(UpperCAmelCase_) , ["labels"]) self.assertEqual(find_labels(UpperCAmelCase_) , ["labels", "next_sentence_label"]) self.assertEqual(find_labels(UpperCAmelCase_) , ["start_positions", "end_positions"]) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' pass self.assertEqual(find_labels(UpperCAmelCase_) , ["labels"]) @require_flax def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any: '''simple docstring''' self.assertEqual(find_labels(UpperCAmelCase_) , []) self.assertEqual(find_labels(UpperCAmelCase_) , []) self.assertEqual(find_labels(UpperCAmelCase_) , []) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' pass self.assertEqual(find_labels(UpperCAmelCase_) , [])
10
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) lowerCAmelCase__ = {'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['BeitFeatureExtractor'] lowerCAmelCase__ = ['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
11
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
0
class lowerCamelCase__: def __init__( self: Dict , UpperCamelCase_: int ): __lowerCamelCase = n __lowerCamelCase = [None] * self.n __lowerCamelCase = 0 # index of the first element __lowerCamelCase = 0 __lowerCamelCase = 0 def __len__( self: Optional[int] ): return self.size def lowerCAmelCase__ ( self: str ): return self.size == 0 def lowerCAmelCase__ ( self: Union[str, Any] ): return False if self.is_empty() else self.array[self.front] def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: List[Any] ): if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __lowerCamelCase = data __lowerCamelCase = (self.rear + 1) % self.n self.size += 1 return self def lowerCAmelCase__ ( self: Union[str, Any] ): if self.size == 0: raise Exception("""UNDERFLOW""" ) __lowerCamelCase = self.array[self.front] __lowerCamelCase = None __lowerCamelCase = (self.front + 1) % self.n self.size -= 1 return temp
12
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
0
import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" _UpperCAmelCase : Tuple = IFInpaintingSuperResolutionPipeline _UpperCAmelCase : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} _UpperCAmelCase : Optional[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''} ) _UpperCAmelCase : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def _SCREAMING_SNAKE_CASE ( self : str): return self._get_superresolution_dummy_components() def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str=0): if str(lowerCAmelCase__).startswith("mps"): SCREAMING_SNAKE_CASE_: Tuple = torch.manual_seed(lowerCAmelCase__) else: SCREAMING_SNAKE_CASE_: str = torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Union[str, Any] = floats_tensor((1, 3, 16, 16) , rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Any = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _SCREAMING_SNAKE_CASE ( self : Dict): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3) def _SCREAMING_SNAKE_CASE ( self : List[Any]): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA") def _SCREAMING_SNAKE_CASE ( self : Any): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1) def _SCREAMING_SNAKE_CASE ( self : int): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): self._test_save_load_local() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
13
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase : int = { """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Tuple = ["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[Any] = [ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[Any] = [ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys _lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
14
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_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =seq_length SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_input_mask SCREAMING_SNAKE_CASE =use_token_type_ids SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =type_vocab_size SCREAMING_SNAKE_CASE =type_sequence_label_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_choices SCREAMING_SNAKE_CASE =scope SCREAMING_SNAKE_CASE =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.use_labels: SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.type_sequence_label_size ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] ,self.num_choices ) SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Optional[int] ): 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 _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=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 _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
0
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[Any] ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"width_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] ,A : List[Any] ,A : Optional[int]=13 ,A : Dict=64 ,A : Optional[Any]=2 ,A : Optional[int]=3 ,A : int="swish" ,A : Tuple=3 ,A : Tuple=32 ,A : int=0.1 ,A : Any=0.02 ,A : Any=True ,A : Optional[int]=True ,A : Tuple=10 ,A : Any=None ,A : Any=0.25 ,A : Tuple=0.0 ,A : Optional[int]=0.0 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = make_divisible(5_12 * width_multiplier ,divisor=8 ) __A = hidden_act __A = conv_kernel_size __A = output_stride __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope __A = width_multiplier __A = ffn_dropout __A = attn_dropout def UpperCamelCase_ ( self : Tuple ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : List[Any] ): return MobileViTVaConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_act=self.hidden_act ,conv_kernel_size=self.conv_kernel_size ,output_stride=self.output_stride ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,width_multiplier=self.width_multiplier ,ffn_dropout=self.ffn_dropout_prob ,attn_dropout=self.attn_dropout_prob ,) def UpperCamelCase_ ( self : int ,A : Any ,A : Any ,A : Union[str, Any] ,A : Optional[int] ): __A = MobileViTVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : Tuple ): __A = self.num_labels __A = MobileViTVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : List[Any] ,A : Dict ,A : List[str] ,A : Union[str, Any] ,A : int ): __A = self.num_labels __A = MobileViTVaForSemanticSegmentation(A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.logits.shape ,( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) __A = model(A ,labels=A ) self.parent.assertEqual( result.logits.shape ,( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : Dict ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) snake_case_ = ( { "feature-extraction": MobileViTVaModel, "image-classification": MobileViTVaForImageClassification, "image-segmentation": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Union[str, Any] ): __A = MobileViTVaModelTester(self ) __A = MobileViTVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileViTV2 does not use inputs_embeds" ) def UpperCamelCase_ ( self : List[str] ): pass @unittest.skip(reason="MobileViTV2 does not support input and output embeddings" ) def UpperCamelCase_ ( self : List[Any] ): pass @unittest.skip(reason="MobileViTV2 does not output attentions" ) def UpperCamelCase_ ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run." ) def UpperCamelCase_ ( self : int ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCamelCase_ ( self : Optional[int] ): pass def UpperCamelCase_ ( self : Dict ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Any ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): def check_hidden_states_output(A : Dict ,A : Optional[int] ,A : Any ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 5 self.assertEqual(len(A ) ,A ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __A = 2 for i in range(len(A ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) ,[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] ,) divisor *= 2 self.assertEqual(self.model_tester.output_stride ,divisor // 2 ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Any ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*A ) @slow def UpperCamelCase_ ( self : Optional[Any] ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileViTVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> Union[str, Any]: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : Any ): return ( MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : str ): __A = MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256" ).to( A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : int ): __A = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) __A = model.to(A ) __A = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) __A = outputs.logits # verify the logits __A = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape ,A ) __A = torch.tensor( [ [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]], [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]], [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]], ] ,device=A ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,A ,atol=1E-4 ) ) @slow def UpperCamelCase_ ( self : List[Any] ): __A = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) __A = model.to(A ) __A = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3" ) __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) __A = outputs.logits.detach().cpu() __A = image_processor.post_process_semantic_segmentation(outputs=A ,target_sizes=[(50, 60)] ) __A = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape ,A ) __A = image_processor.post_process_semantic_segmentation(outputs=A ) __A = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape ,A )
15
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
0
"""simple docstring""" import os def __UpperCAmelCase ( ) -> int: with open(os.path.dirname(__lowerCamelCase ) + '''/p022_names.txt''' ) as file: lowercase__ : List[Any] = str(file.readlines()[0] ) lowercase__ : Dict = names.replace('''"''' , '''''' ).split(''',''' ) names.sort() lowercase__ : int = 0 lowercase__ : Optional[Any] = 0 for i, name in enumerate(__lowerCamelCase ): for letter in name: name_score += ord(__lowerCamelCase ) - 64 total_score += (i + 1) * name_score lowercase__ : List[str] = 0 return total_score if __name__ == "__main__": print(solution())
16
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
0
"""simple docstring""" from math import pi, sqrt def _A ( UpperCamelCase_ : float) -> float: '''simple docstring''' if num <= 0: raise ValueError("math domain error") if num > 171.5: raise OverflowError("math range error") elif num - int(UpperCamelCase_) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer") elif num == 0.5: return sqrt(UpperCamelCase_) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1) def _A ( ) -> None: '''simple docstring''' assert gamma(0.5) == sqrt(UpperCamelCase_) assert gamma(1) == 1.0 assert gamma(2) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _a = 1.0 while num: _a = float(input('Gamma of: ')) print(F"gamma({num}) = {gamma(num)}") print('\nEnter 0 to exit...')
17
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
0
from math import factorial class a__ : def __init__( self : List[str],_A : Tuple,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = real if isinstance(_A,_A ): SCREAMING_SNAKE_CASE_ : Tuple = [1] * rank else: SCREAMING_SNAKE_CASE_ : Optional[Any] = rank def __repr__( self : List[Any] ): """simple docstring""" return ( F'{self.real}+' F'{"+".join(str(_A )+"E"+str(n+1 )for n,dual in enumerate(self.duals ) )}' ) def __UpperCamelCase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real,_A ) def __add__( self : Any,_A : List[Any] ): """simple docstring""" if not isinstance(_A,_A ): return Dual(self.real + other,self.duals ) SCREAMING_SNAKE_CASE_ : str = self.duals.copy() SCREAMING_SNAKE_CASE_ : Union[str, Any] = other.duals.copy() if len(_A ) > len(_A ): o_dual.extend([1] * (len(_A ) - len(_A )) ) elif len(_A ) < len(_A ): s_dual.extend([1] * (len(_A ) - len(_A )) ) SCREAMING_SNAKE_CASE_ : int = [] for i in range(len(_A ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real,_A ) A = __add__ def __sub__( self : Any,_A : Union[str, Any] ): """simple docstring""" return self + other * -1 def __mul__( self : Tuple,_A : Any ): """simple docstring""" if not isinstance(_A,_A ): SCREAMING_SNAKE_CASE_ : int = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other,_A ) SCREAMING_SNAKE_CASE_ : str = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real,_A ) A = __mul__ def __truediv__( self : Optional[Any],_A : Dict ): """simple docstring""" if not isinstance(_A,_A ): SCREAMING_SNAKE_CASE_ : Dict = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other,_A ) raise ValueError def __floordiv__( self : List[str],_A : Any ): """simple docstring""" if not isinstance(_A,_A ): SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other,_A ) raise ValueError def __pow__( self : Optional[Any],_A : Any ): """simple docstring""" if n < 0 or isinstance(_A,_A ): raise ValueError("power must be a positive integer" ) if n == 0: return 1 if n == 1: return self SCREAMING_SNAKE_CASE_ : Union[str, Any] = self for _ in range(n - 1 ): x *= self return x def _snake_case ( lowerCAmelCase : Tuple , lowerCAmelCase : List[str] , lowerCAmelCase : Any ): """simple docstring""" if not callable(lowerCAmelCase ): raise ValueError("differentiate() requires a function as input for func" ) if not isinstance(lowerCAmelCase , (float, int) ): raise ValueError("differentiate() requires a float as input for position" ) if not isinstance(lowerCAmelCase , lowerCAmelCase ): raise ValueError("differentiate() requires an int as input for order" ) SCREAMING_SNAKE_CASE_ : Tuple = Dual(lowerCAmelCase , 1 ) SCREAMING_SNAKE_CASE_ : Dict = func(lowerCAmelCase ) if order == 0: return result.real return result.duals[order - 1] * factorial(lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() def _snake_case ( lowerCAmelCase : Any ): """simple docstring""" return y**2 * y**4 print(differentiate(f, 9, 2))
18
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
0
import math def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ = 0 , lowerCamelCase__ = 0 ): lowerCamelCase_ = end or len(lowerCamelCase__ ) for i in range(lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = i lowerCamelCase_ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: lowerCamelCase_ = array[temp_index - 1] temp_index -= 1 lowerCamelCase_ = temp_index_value return array def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): # Max Heap lowerCamelCase_ = index lowerCamelCase_ = 2 * index + 1 # Left Node lowerCamelCase_ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: lowerCamelCase_ = left_index if right_index < heap_size and array[largest] < array[right_index]: lowerCamelCase_ = right_index if largest != index: lowerCamelCase_ , lowerCamelCase_ = array[largest], array[index] heapify(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = len(lowerCamelCase__ ) for i in range(n // 2 , -1 , -1 ): heapify(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for i in range(n - 1 , 0 , -1 ): lowerCamelCase_ , lowerCamelCase_ = array[0], array[i] heapify(lowerCamelCase__ , 0 , lowerCamelCase__ ) return array def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = low lowerCamelCase_ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i lowerCamelCase_ , lowerCamelCase_ = array[j], array[i] i += 1 def lowerCamelCase_ ( lowerCamelCase__ ): if len(lowerCamelCase__ ) == 0: return array lowerCamelCase_ = 2 * math.ceil(math.loga(len(lowerCamelCase__ ) ) ) lowerCamelCase_ = 1_6 return intro_sort(lowerCamelCase__ , 0 , len(lowerCamelCase__ ) , lowerCamelCase__ , lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): while end - start > size_threshold: if max_depth == 0: return heap_sort(lowerCamelCase__ ) max_depth -= 1 lowerCamelCase_ = median_of_a(lowerCamelCase__ , lowerCamelCase__ , start + ((end - start) // 2) + 1 , end - 1 ) lowerCamelCase_ = partition(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) intro_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_ = p return insertion_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() __A =input('''Enter numbers separated by a comma : ''').strip() __A =[float(item) for item in user_input.split(''',''')] print(sort(unsorted))
19
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =encoder_ffn_dim SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =encoder_attention_heads SCREAMING_SNAKE_CASE =decoder_ffn_dim SCREAMING_SNAKE_CASE =decoder_layers SCREAMING_SNAKE_CASE =decoder_attention_heads SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING lowercase : int = logging.get_logger(__name__) lowercase : Tuple = { """Salesforce/instruct-blip-flan-t5""": """https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json""", } class __snake_case ( lowerCAmelCase ): _a : str= "instructblip_vision_model" def __init__( self ,snake_case=1408 ,snake_case=6144 ,snake_case=39 ,snake_case=16 ,snake_case=224 ,snake_case=14 ,snake_case="gelu" ,snake_case=1e-6 ,snake_case=0.0 ,snake_case=1e-10 ,snake_case=True ,**snake_case ,): '''simple docstring''' super().__init__(**snake_case ) lowercase : Any = hidden_size lowercase : Optional[int] = intermediate_size lowercase : Optional[int] = num_hidden_layers lowercase : str = num_attention_heads lowercase : List[Any] = patch_size lowercase : Any = image_size lowercase : List[Any] = initializer_range lowercase : Optional[Any] = attention_dropout lowercase : str = layer_norm_eps lowercase : Optional[int] = hidden_act lowercase : Union[str, Any] = qkv_bias @classmethod def _SCREAMING_SNAKE_CASE ( cls ,snake_case ,**snake_case ): '''simple docstring''' cls._set_token_in_kwargs(snake_case ) lowercase , lowercase : Optional[int] = cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": lowercase : Tuple = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(snake_case ,**snake_case ) class __snake_case ( lowerCAmelCase ): _a : List[str]= "instructblip_qformer" def __init__( self ,snake_case=30522 ,snake_case=768 ,snake_case=12 ,snake_case=12 ,snake_case=3072 ,snake_case="gelu" ,snake_case=0.1 ,snake_case=0.1 ,snake_case=512 ,snake_case=0.02 ,snake_case=1e-12 ,snake_case=0 ,snake_case="absolute" ,snake_case=2 ,snake_case=1408 ,**snake_case ,): '''simple docstring''' super().__init__(pad_token_id=snake_case ,**snake_case ) lowercase : Tuple = vocab_size lowercase : str = hidden_size lowercase : Optional[Any] = num_hidden_layers lowercase : List[str] = num_attention_heads lowercase : List[str] = hidden_act lowercase : Optional[int] = intermediate_size lowercase : str = hidden_dropout_prob lowercase : Dict = attention_probs_dropout_prob lowercase : Optional[Any] = max_position_embeddings lowercase : Any = initializer_range lowercase : List[Any] = layer_norm_eps lowercase : Optional[Any] = position_embedding_type lowercase : Dict = cross_attention_frequency lowercase : int = encoder_hidden_size @classmethod def _SCREAMING_SNAKE_CASE ( cls ,snake_case ,**snake_case ): '''simple docstring''' cls._set_token_in_kwargs(snake_case ) lowercase , lowercase : Tuple = cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": lowercase : Any = config_dict["""qformer_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(snake_case ,**snake_case ) class __snake_case ( lowerCAmelCase ): _a : List[str]= "instructblip" _a : List[Any]= True def __init__( self ,snake_case=None ,snake_case=None ,snake_case=None ,snake_case=32 ,**snake_case ): '''simple docstring''' super().__init__(**snake_case ) if vision_config is None: lowercase : int = {} logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values.""" ) if qformer_config is None: lowercase : Tuple = {} logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.""" ) if text_config is None: lowercase : Tuple = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) lowercase : Dict = InstructBlipVisionConfig(**snake_case ) lowercase : Optional[Any] = InstructBlipQFormerConfig(**snake_case ) lowercase : Optional[int] = text_config["""model_type"""] if """model_type""" in text_config else """opt""" lowercase : Optional[Any] = CONFIG_MAPPING[text_model_type](**snake_case ) lowercase : Union[str, Any] = self.text_config.tie_word_embeddings lowercase : Optional[int] = self.text_config.is_encoder_decoder lowercase : Tuple = num_query_tokens lowercase : int = self.vision_config.hidden_size lowercase : Optional[Any] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES lowercase : Tuple = 1.0 lowercase : int = 0.02 @classmethod def _SCREAMING_SNAKE_CASE ( cls ,snake_case ,snake_case ,snake_case ,**snake_case ,): '''simple docstring''' return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = copy.deepcopy(self.__dict__ ) lowercase : str = self.vision_config.to_dict() lowercase : int = self.qformer_config.to_dict() lowercase : List[Any] = self.text_config.to_dict() lowercase : Optional[int] = self.__class__.model_type return output
20
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
0