code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session' ) def __magic_name__ ( ) -> Dict: _lowercase : Optional[int] = 10 _lowercase : str = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string' ) ), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'] ) ), 'answers': datasets.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), 'id': datasets.Value('int64' ), } ) _lowercase : Dict = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(SCREAMING_SNAKE_CASE ) ), } , features=SCREAMING_SNAKE_CASE , ) return dataset @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : int = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=SCREAMING_SNAKE_CASE ) return filename # FILE_CONTENT + files UpperCamelCase = "\\n Text data.\n Second line of data." @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Tuple: _lowercase : Optional[int] = tmp_path_factory.mktemp('data' ) / 'file.txt' _lowercase : int = FILE_CONTENT with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return filename @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: import bza _lowercase : Dict = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' _lowercase : Optional[int] = bytes(SCREAMING_SNAKE_CASE , 'utf-8' ) with bza.open(SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> str: import gzip _lowercase : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) _lowercase : Union[str, Any] = bytes(SCREAMING_SNAKE_CASE , 'utf-8' ) with gzip.open(SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[str]: if datasets.config.LZ4_AVAILABLE: import lza.frame _lowercase : List[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' _lowercase : Tuple = bytes(SCREAMING_SNAKE_CASE , 'utf-8' ) with lza.frame.open(SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: if datasets.config.PY7ZR_AVAILABLE: import pyazr _lowercase : Tuple = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(SCREAMING_SNAKE_CASE , 'w' ) as archive: archive.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: import tarfile _lowercase : List[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Any: import lzma _lowercase : str = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' _lowercase : Dict = bytes(SCREAMING_SNAKE_CASE , 'utf-8' ) with lzma.open(SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: import zipfile _lowercase : int = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' _lowercase : List[Any] = bytes(SCREAMING_SNAKE_CASE , 'utf-8' ) with zstd.open(SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Optional[int]: _lowercase : Dict = tmp_path_factory.mktemp('data' ) / 'file.xml' _lowercase : List[str] = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return filename UpperCamelCase = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] UpperCamelCase = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] UpperCamelCase = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } UpperCamelCase = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] UpperCamelCase = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope='session' ) def __magic_name__ ( ) -> Dict: return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : Dict = datasets.Dataset.from_dict(SCREAMING_SNAKE_CASE ) _lowercase : Dict = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(SCREAMING_SNAKE_CASE ) ) as con: _lowercase : Union[str, Any] = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)' ) for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(SCREAMING_SNAKE_CASE , 'w' , newline='' ) as f: _lowercase : Dict = csv.DictWriter(SCREAMING_SNAKE_CASE , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Any: _lowercase : Dict = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(SCREAMING_SNAKE_CASE , 'w' , newline='' ) as f: _lowercase : Union[str, Any] = csv.DictWriter(SCREAMING_SNAKE_CASE , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: import bza _lowercase : int = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(SCREAMING_SNAKE_CASE , 'rb' ) as f: _lowercase : str = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: _lowercase : List[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: _lowercase : int = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV' ) ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: _lowercase : Any = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) _lowercase : str = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(SCREAMING_SNAKE_CASE , 'wb' ) as f: _lowercase : List[Any] = pq.ParquetWriter(SCREAMING_SNAKE_CASE , schema=SCREAMING_SNAKE_CASE ) _lowercase : Any = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(SCREAMING_SNAKE_CASE ) )] for k in DATA[0]} , schema=SCREAMING_SNAKE_CASE ) writer.write_table(SCREAMING_SNAKE_CASE ) writer.close() return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _lowercase : Dict = {'data': DATA} with open(SCREAMING_SNAKE_CASE , 'w' ) as f: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : Optional[int] = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _lowercase : Optional[Any] = {'data': DATA_DICT_OF_LISTS} with open(SCREAMING_SNAKE_CASE , 'w' ) as f: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> str: _lowercase : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA: f.write(json.dumps(SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : int = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA: f.write(json.dumps(SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Dict: _lowercase : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA_312: f.write(json.dumps(SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> str: _lowercase : List[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA_STR: f.write(json.dumps(SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: import gzip _lowercase : Union[str, Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(SCREAMING_SNAKE_CASE , 'rb' ) as orig_file: with gzip.open(SCREAMING_SNAKE_CASE , 'wb' ) as zipped_file: zipped_file.writelines(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: import gzip _lowercase : Optional[Any] = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(SCREAMING_SNAKE_CASE , 'rb' ) as orig_file: with gzip.open(SCREAMING_SNAKE_CASE , 'wb' ) as zipped_file: zipped_file.writelines(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : List[str] = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: _lowercase : List[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('nested' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) f.add(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(SCREAMING_SNAKE_CASE , arcname=os.path.join('nested' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Tuple: _lowercase : str = ['0', '1', '2', '3'] _lowercase : Tuple = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[str]: _lowercase : Optional[int] = ['0', '1', '2', '3'] _lowercase : int = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : Tuple = ['0', '1', '2', '3'] _lowercase : str = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(SCREAMING_SNAKE_CASE , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: _lowercase : str = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: _lowercase : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename('unsupported.ext' ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> Any: _lowercase : Tuple = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) _lowercase : str = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( ) -> Any: return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def __magic_name__ ( ) -> Optional[Any]: return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: _lowercase : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ) ) f.write(SCREAMING_SNAKE_CASE , arcname=os.path.basename(SCREAMING_SNAKE_CASE ).replace('.jpg' , '2.jpg' ) ) return path @pytest.fixture(scope='session' ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> int: _lowercase : Dict = tmp_path_factory.mktemp('data_dir' ) (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / 'subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden file with open(data_dir / 'subdir' / '.test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / '.subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) return data_dir
66
import argparse import os import re import packaging.version SCREAMING_SNAKE_CASE__ = "examples/" SCREAMING_SNAKE_CASE__ = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } SCREAMING_SNAKE_CASE__ = { "init": "src/transformers/__init__.py", "setup": "setup.py", } SCREAMING_SNAKE_CASE__ = "README.md" def lowercase ( a , a , a ): '''simple docstring''' with open(a , "r" , encoding="utf-8" , newline="\n" ) as f: SCREAMING_SNAKE_CASE_ :Dict = f.read() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Union[str, Any] = REPLACE_PATTERNS[pattern] SCREAMING_SNAKE_CASE_ :List[str] = replace.replace("VERSION" , a ) SCREAMING_SNAKE_CASE_ :str = re_pattern.sub(a , a ) with open(a , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(a ) def lowercase ( a ): '''simple docstring''' for folder, directories, fnames in os.walk(a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(a , a ) , a , pattern="examples" ) def lowercase ( a , a=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(a , a , a ) if not patch: update_version_in_examples(a ) def lowercase ( ): '''simple docstring''' SCREAMING_SNAKE_CASE_ :int = "🤗 Transformers currently provides the following architectures" SCREAMING_SNAKE_CASE_ :Any = "1. Want to contribute a new model?" with open(a , "r" , encoding="utf-8" , newline="\n" ) as f: SCREAMING_SNAKE_CASE_ :List[str] = f.readlines() # Find the start of the list. SCREAMING_SNAKE_CASE_ :int = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ :int = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): SCREAMING_SNAKE_CASE_ :Union[str, Any] = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(a , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(a ) def lowercase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: SCREAMING_SNAKE_CASE_ :str = f.read() SCREAMING_SNAKE_CASE_ :Optional[int] = REPLACE_PATTERNS["init"][0].search(a ).groups()[0] return packaging.version.parse(a ) def lowercase ( a=False ): '''simple docstring''' SCREAMING_SNAKE_CASE_ :str = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: SCREAMING_SNAKE_CASE_ :int = default_version.base_version elif patch: SCREAMING_SNAKE_CASE_ :Union[str, Any] = F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: SCREAMING_SNAKE_CASE_ :List[str] = F"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. SCREAMING_SNAKE_CASE_ :List[Any] = input(F"Which version are you releasing? [{default_version}]" ) if len(a ) == 0: SCREAMING_SNAKE_CASE_ :Any = default_version print(F"Updating version to {version}." ) global_version_update(a , patch=a ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def lowercase ( ): '''simple docstring''' SCREAMING_SNAKE_CASE_ :Optional[Any] = get_version() SCREAMING_SNAKE_CASE_ :Optional[Any] = F"{current_version.major}.{current_version.minor + 1}.0.dev0" SCREAMING_SNAKE_CASE_ :str = current_version.base_version # Check with the user we got that right. SCREAMING_SNAKE_CASE_ :Any = input(F"Which version are we developing now? [{dev_version}]" ) if len(a ) == 0: SCREAMING_SNAKE_CASE_ :Optional[Any] = dev_version print(F"Updating version to {version}." ) global_version_update(a ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") SCREAMING_SNAKE_CASE__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
631
0
'''simple docstring''' import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def SCREAMING_SNAKE_CASE__ ( __A , __A , __A=[] ) -> List[Any]: _snake_case = size[0] - overlap_pixels * 2 _snake_case = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels _snake_case = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 _snake_case = np.pad(__snake_case , mode='linear_ramp' , pad_width=__snake_case , end_values=0 ) if "l" in remove_borders: _snake_case = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: _snake_case = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: _snake_case = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: _snake_case = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> Any: return max(__snake_case , min(__snake_case , __snake_case ) ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> Tuple: return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> str: _snake_case = list(__snake_case ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap _snake_case = clamp_rect(__snake_case , [0, 0] , [image_size[0], image_size[1]] ) return rect def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A ) -> int: _snake_case = Image.new('RGB' , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__snake_case , (original_slice, 0) ) return result def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> str: _snake_case = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) _snake_case = tile.crop(__snake_case ) return tile def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> Optional[Any]: _snake_case = n % d return n - divisor class __UpperCAmelCase ( _lowerCamelCase ): def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 3_50 , ): """simple docstring""" super().__init__( vae=__lowerCAmelCase , text_encoder=__lowerCAmelCase , tokenizer=__lowerCAmelCase , unet=__lowerCAmelCase , low_res_scheduler=__lowerCAmelCase , scheduler=__lowerCAmelCase , max_noise_level=__lowerCAmelCase , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" torch.manual_seed(0 ) _snake_case = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) _snake_case = add_overlap_rect(__lowerCAmelCase , __lowerCAmelCase , image.size ) _snake_case = image.crop(__lowerCAmelCase ) _snake_case = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] _snake_case = translated_slice_x - (original_image_slice / 2) _snake_case = max(0 , __lowerCAmelCase ) _snake_case = squeeze_tile(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) _snake_case = to_input.size _snake_case = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) _snake_case = super(__lowerCAmelCase , self ).__call__(image=__lowerCAmelCase , **__lowerCAmelCase ).images[0] _snake_case = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) _snake_case = unsqueeze_tile(__lowerCAmelCase , __lowerCAmelCase ) _snake_case = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) _snake_case = [] if x == 0: remove_borders.append('l' ) elif crop_rect[2] == image.size[0]: remove_borders.append('r' ) if y == 0: remove_borders.append('t' ) elif crop_rect[3] == image.size[1]: remove_borders.append('b' ) _snake_case = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__lowerCAmelCase ) , mode='L' , ) final_image.paste( __lowerCAmelCase , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __lowerCAmelCase ) @torch.no_grad() def __call__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 75 , lowerCAmelCase_ = 9.0 , lowerCAmelCase_ = 50 , lowerCAmelCase_ = None , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 0.0 , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 1_28 , lowerCAmelCase_ = 32 , lowerCAmelCase_ = 32 , ): """simple docstring""" _snake_case = Image.new('RGB' , (image.size[0] * 4, image.size[1] * 4) ) _snake_case = math.ceil(image.size[0] / tile_size ) _snake_case = math.ceil(image.size[1] / tile_size ) _snake_case = tcx * tcy _snake_case = 0 for y in range(__lowerCAmelCase ): for x in range(__lowerCAmelCase ): self._process_tile( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , prompt=__lowerCAmelCase , num_inference_steps=__lowerCAmelCase , guidance_scale=__lowerCAmelCase , noise_level=__lowerCAmelCase , negative_prompt=__lowerCAmelCase , num_images_per_prompt=__lowerCAmelCase , eta=__lowerCAmelCase , generator=__lowerCAmelCase , latents=__lowerCAmelCase , ) current_count += 1 if callback is not None: callback({'progress': current_count / total_tile_count, 'image': final_image} ) return final_image def SCREAMING_SNAKE_CASE__ ( ) -> List[Any]: _snake_case = 'stabilityai/stable-diffusion-x4-upscaler' _snake_case = StableDiffusionTiledUpscalePipeline.from_pretrained(__snake_case , revision='fp16' , torch_dtype=torch.floataa ) _snake_case = pipe.to('cuda' ) _snake_case = Image.open('../../docs/source/imgs/diffusers_library.jpg' ) def callback(__A ): print(F'progress: {obj["progress"]:.4f}' ) obj["image"].save('diffusers_library_progress.jpg' ) _snake_case = pipe(image=__snake_case , prompt='Black font, white background, vector' , noise_level=40 , callback=__snake_case ) final_image.save('diffusers_library.jpg' ) if __name__ == "__main__": main()
707
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=sys.maxsize ): """simple docstring""" _snake_case = 'bilinear' _snake_case = max_size _snake_case = short_edge_length def __call__( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = [] for img in imgs: _snake_case , _snake_case = img.shape[:2] # later: provide list and randomly choose index for resize _snake_case = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img _snake_case = size * 1.0 / min(lowerCAmelCase_ , lowerCAmelCase_ ) if h < w: _snake_case , _snake_case = size, scale * w else: _snake_case , _snake_case = scale * h, size if max(lowerCAmelCase_ , lowerCAmelCase_ ) > self.max_size: _snake_case = self.max_size * 1.0 / max(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = newh * scale _snake_case = neww * scale _snake_case = int(neww + 0.5 ) _snake_case = int(newh + 0.5 ) if img.dtype == np.uinta: _snake_case = Image.fromarray(lowerCAmelCase_ ) _snake_case = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) _snake_case = np.asarray(lowerCAmelCase_ ) else: _snake_case = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw _snake_case = nn.functional.interpolate( lowerCAmelCase_ , (newh, neww) , mode=self.interp_method , align_corners=lowerCAmelCase_ ).squeeze(0 ) img_augs.append(lowerCAmelCase_ ) return img_augs class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) _snake_case = cfg.INPUT.FORMAT _snake_case = cfg.SIZE_DIVISIBILITY _snake_case = cfg.PAD_VALUE _snake_case = cfg.INPUT.MAX_SIZE_TEST _snake_case = cfg.MODEL.DEVICE _snake_case = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _snake_case = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _snake_case = lambda lowerCAmelCase_ : (x - self.pixel_mean) / self.pixel_std def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = tuple(max(lowerCAmelCase_ ) for s in zip(*[img.shape for img in images] ) ) _snake_case = [im.shape[-2:] for im in images] _snake_case = [ nn.functional.pad( lowerCAmelCase_ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(lowerCAmelCase_ , lowerCAmelCase_ ) ] return torch.stack(lowerCAmelCase_ ), torch.tensor(lowerCAmelCase_ ) def __call__( self , lowerCAmelCase_ , lowerCAmelCase_=False ): """simple docstring""" with torch.no_grad(): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): _snake_case = [images] if single_image: assert len(lowerCAmelCase_ ) == 1 for i in range(len(lowerCAmelCase_ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(lowerCAmelCase_ , images.pop(lowerCAmelCase_ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( lowerCAmelCase_ , torch.as_tensor(img_tensorize(images.pop(lowerCAmelCase_ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge _snake_case = torch.tensor([im.shape[:2] for im in images] ) _snake_case = self.aug(lowerCAmelCase_ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic _snake_case = [self.normalizer(lowerCAmelCase_ ) for x in images] # now pad them to do the following operations _snake_case , _snake_case = self.pad(lowerCAmelCase_ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad _snake_case = torch.true_divide(lowerCAmelCase_ , lowerCAmelCase_ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> List[Any]: boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> List[Any]: assert torch.isfinite(__A ).all(), "Box tensor contains infinite or NaN!" _snake_case , _snake_case = box_size tensor[:, 0].clamp_(min=0 , max=__A ) tensor[:, 1].clamp_(min=0 , max=__A ) tensor[:, 2].clamp_(min=0 , max=__A ) tensor[:, 3].clamp_(min=0 , max=__A )
542
0
'''simple docstring''' import math def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float: if ( not isinstance(__UpperCamelCase ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return apparent_power * power_factor def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float: if ( not isinstance(__UpperCamelCase ,(int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
42
# Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file lowerCAmelCase = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.''' def _lowerCamelCase( lowercase__=None ) -> Optional[int]: '''simple docstring''' if subparsers is not None: __lowercase= subparsers.add_parser('tpu-config' , description=_description ) else: __lowercase= argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments __lowercase= parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=lowercase__ , default=lowercase__ , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=lowercase__ , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=lowercase__ , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) __lowercase= parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=lowercase__ , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=lowercase__ ) return parser def _lowerCamelCase( lowercase__ ) -> Dict: '''simple docstring''' __lowercase= None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowercase__ ): __lowercase= load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __lowercase= defaults.command_file if not args.command and defaults.commands is not None: __lowercase= defaults.commands if not args.tpu_name: __lowercase= defaults.tpu_name if not args.tpu_zone: __lowercase= defaults.tpu_zone if args.accelerate_version == "dev": __lowercase= 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": __lowercase= 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , lowercase__ ): __lowercase= F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: __lowercase= [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowercase__ ): __lowercase= [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __lowercase= ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command __lowercase= '; '.join(lowercase__ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __lowercase= ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(lowercase__ )}' ) return subprocess.run(lowercase__ ) print('Successfully setup pod.' ) def _lowerCamelCase( ) -> Union[str, Any]: '''simple docstring''' __lowercase= tpu_command_parser() __lowercase= parser.parse_args() tpu_command_launcher(lowercase__ )
230
0
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging _UpperCamelCase : List[str] = logging.get_logger(__name__) _UpperCamelCase : Optional[Any] = {'vocab_file': 'spiece.model'} _UpperCamelCase : int = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', } } _UpperCamelCase : Tuple = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } # Segments (not really needed) _UpperCamelCase : Optional[int] = 0 _UpperCamelCase : Optional[int] = 1 _UpperCamelCase : List[str] = 2 _UpperCamelCase : Any = 3 _UpperCamelCase : Union[str, Any] = 4 class snake_case__ ( UpperCamelCase): a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = "left" def __init__( self : Tuple , _A : Tuple , _A : List[Any]=False , _A : List[Any]=True , _A : int=False , _A : List[str]="<s>" , _A : List[str]="</s>" , _A : Tuple="<unk>" , _A : Optional[int]="<sep>" , _A : int="<pad>" , _A : List[str]="<cls>" , _A : Optional[int]="<mask>" , _A : Union[str, Any]=["<eop>", "<eod>"] , _A : Optional[Dict[str, Any]] = None , **_A : List[str] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ : Optional[Any] = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token UpperCAmelCase_ : List[str] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , additional_special_tokens=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) UpperCAmelCase_ : Dict = 3 UpperCAmelCase_ : Optional[Any] = do_lower_case UpperCAmelCase_ : List[Any] = remove_space UpperCAmelCase_ : Dict = keep_accents UpperCAmelCase_ : int = vocab_file UpperCAmelCase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_A ) @property def A ( self : List[Any] ) -> Union[str, Any]: return len(self.sp_model ) def A ( self : List[str] ) -> List[str]: UpperCAmelCase_ : List[Any] = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[Any] ) -> Optional[Any]: UpperCAmelCase_ : str = self.__dict__.copy() UpperCAmelCase_ : Optional[Any] = None return state def __setstate__( self : Tuple , _A : str ) -> Any: UpperCAmelCase_ : Any = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase_ : int = {} UpperCAmelCase_ : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A ( self : Dict , _A : List[str] ) -> str: if self.remove_space: UpperCAmelCase_ : Tuple = ''' '''.join(inputs.strip().split() ) else: UpperCAmelCase_ : Optional[Any] = inputs UpperCAmelCase_ : Any = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: UpperCAmelCase_ : str = unicodedata.normalize('''NFKD''' , _A ) UpperCAmelCase_ : str = ''''''.join([c for c in outputs if not unicodedata.combining(_A )] ) if self.do_lower_case: UpperCAmelCase_ : List[Any] = outputs.lower() return outputs def A ( self : List[str] , _A : str ) -> List[str]: UpperCAmelCase_ : Dict = self.preprocess_text(_A ) UpperCAmelCase_ : Optional[int] = self.sp_model.encode(_A , out_type=_A ) UpperCAmelCase_ : List[Any] = [] for piece in pieces: if len(_A ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): UpperCAmelCase_ : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(_A , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: UpperCAmelCase_ : Dict = cur_pieces[1:] else: UpperCAmelCase_ : Optional[Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_A ) else: new_pieces.append(_A ) return new_pieces def A ( self : int , _A : str ) -> Dict: return self.sp_model.PieceToId(_A ) def A ( self : List[Any] , _A : Dict ) -> Union[str, Any]: return self.sp_model.IdToPiece(_A ) def A ( self : Optional[Any] , _A : Optional[Any] ) -> str: UpperCAmelCase_ : List[Any] = ''''''.join(_A ).replace(_A , ''' ''' ).strip() return out_string def A ( self : Any , _A : List[int] , _A : bool = False , _A : bool = None , _A : bool = True , **_A : Any , ) -> str: UpperCAmelCase_ : Optional[int] = kwargs.pop('''use_source_tokenizer''' , _A ) UpperCAmelCase_ : Tuple = self.convert_ids_to_tokens(_A , skip_special_tokens=_A ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 UpperCAmelCase_ : Any = [] UpperCAmelCase_ : str = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A ) ) UpperCAmelCase_ : List[Any] = [] sub_texts.append(_A ) else: current_sub_text.append(_A ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_A ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens UpperCAmelCase_ : Optional[int] = ''''''.join(_A ) UpperCAmelCase_ : List[Any] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: UpperCAmelCase_ : Optional[Any] = self.clean_up_tokenization(_A ) return clean_text else: return text def A ( self : Dict , _A : List[int] , _A : Optional[List[int]] = None ) -> List[int]: UpperCAmelCase_ : List[Any] = [self.sep_token_id] UpperCAmelCase_ : List[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def A ( self : int , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) if token_ids_a is not None: return ([0] * len(_A )) + [1] + ([0] * len(_A )) + [1, 1] return ([0] * len(_A )) + [1, 1] def A ( self : Any , _A : List[int] , _A : Optional[List[int]] = None ) -> List[int]: UpperCAmelCase_ : Dict = [self.sep_token_id] UpperCAmelCase_ : Tuple = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def A ( self : List[str] , _A : str , _A : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(_A ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return UpperCAmelCase_ : str = os.path.join( _A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _A ) elif not os.path.isfile(self.vocab_file ): with open(_A , '''wb''' ) as fi: UpperCAmelCase_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,)
703
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( UpperCamelCase , unittest.TestCase): a_ = BioGptTokenizer a_ = False def A ( self : int ) -> List[Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCAmelCase_ : Any = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] UpperCAmelCase_ : List[str] = dict(zip(_A , range(len(_A ) ) ) ) UpperCAmelCase_ : Tuple = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] UpperCAmelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(_A ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(_A ) ) def A ( self : List[Any] , _A : Optional[Any] ) -> Any: UpperCAmelCase_ : int = '''lower newer''' UpperCAmelCase_ : Tuple = '''lower newer''' return input_text, output_text def A ( self : str ) -> Optional[Any]: UpperCAmelCase_ : List[Any] = BioGptTokenizer(self.vocab_file , self.merges_file ) UpperCAmelCase_ : Tuple = '''lower''' UpperCAmelCase_ : List[Any] = ['''low''', '''er</w>'''] UpperCAmelCase_ : List[Any] = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) UpperCAmelCase_ : Any = tokens + ['''<unk>'''] UpperCAmelCase_ : List[Any] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , _A ) @slow def A ( self : int ) -> List[str]: UpperCAmelCase_ : Optional[Any] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : List[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=_A ) UpperCAmelCase_ : Any = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_A ) UpperCAmelCase_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A ) UpperCAmelCase_ : Optional[int] = tokenizer.build_inputs_with_special_tokens(_A , _A ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
216
0
def A ( _lowerCamelCase ): '''simple docstring''' if not isinstance(_lowerCamelCase , _lowerCamelCase ): _lowerCAmelCase : Union[str, Any] = F"Input value of [number={number}] must be an integer" raise TypeError(_lowerCamelCase ) if number < 1: _lowerCAmelCase : Tuple = F"Input value of [number={number}] must be > 0" raise ValueError(_lowerCamelCase ) _lowerCAmelCase : Dict = 1 for i in range(1 , _lowerCamelCase ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
500
import math def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = [True] * n _lowerCAmelCase : Optional[int] = False _lowerCAmelCase : Tuple = False _lowerCAmelCase : Optional[Any] = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): _lowerCAmelCase : Union[str, Any] = i * 2 while index < n: _lowerCAmelCase : int = False _lowerCAmelCase : Optional[Any] = index + i _lowerCAmelCase : str = [2] for i in range(3 , _lowerCamelCase , 2 ): if is_prime[i]: primes.append(_lowerCamelCase ) return primes def A ( _lowerCamelCase = 999_966_663_333 ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = math.floor(math.sqrt(_lowerCamelCase ) ) + 100 _lowerCAmelCase : str = prime_sieve(_lowerCamelCase ) _lowerCAmelCase : List[str] = 0 _lowerCAmelCase : Union[str, Any] = 0 _lowerCAmelCase : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: _lowerCAmelCase : int = primes[prime_index + 1] _lowerCAmelCase : Dict = last_prime**2 _lowerCAmelCase : Optional[Any] = next_prime**2 # Get numbers divisible by lps(current) _lowerCAmelCase : List[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) _lowerCAmelCase : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps _lowerCAmelCase : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair _lowerCAmelCase : Optional[int] = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
500
1
"""simple docstring""" def _snake_case ( UpperCamelCase : str , UpperCamelCase : Dict ): UpperCAmelCase : Union[str, Any] = len(UpperCamelCase ) UpperCAmelCase : List[str] = len(UpperCamelCase ) UpperCAmelCase : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) UpperCAmelCase : Optional[Any] = [] for char_count in range(UpperCamelCase ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(UpperCamelCase ) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
705
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging A: Optional[int] = logging.get_logger(__name__) A: Union[str, Any] = { "EleutherAI/gpt-neo-1.3B": "https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json", # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : List[str] = 'gpt_neo' __lowerCAmelCase : Any = ['past_key_values'] __lowerCAmelCase : int = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self , _SCREAMING_SNAKE_CASE=50257 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=24 , _SCREAMING_SNAKE_CASE=[[["global", "local"], 12]] , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=50256 , _SCREAMING_SNAKE_CASE=50256 , **_SCREAMING_SNAKE_CASE , ) -> str: '''simple docstring''' UpperCAmelCase : int = vocab_size UpperCAmelCase : List[Any] = max_position_embeddings UpperCAmelCase : str = hidden_size UpperCAmelCase : Dict = num_layers UpperCAmelCase : List[Any] = num_heads UpperCAmelCase : Optional[Any] = intermediate_size UpperCAmelCase : Dict = window_size UpperCAmelCase : int = activation_function UpperCAmelCase : Tuple = resid_dropout UpperCAmelCase : int = embed_dropout UpperCAmelCase : Optional[int] = attention_dropout UpperCAmelCase : Optional[int] = classifier_dropout UpperCAmelCase : Any = layer_norm_epsilon UpperCAmelCase : Union[str, Any] = initializer_range UpperCAmelCase : List[str] = use_cache UpperCAmelCase : Union[str, Any] = bos_token_id UpperCAmelCase : str = eos_token_id UpperCAmelCase : Union[str, Any] = attention_types UpperCAmelCase : int = self.expand_attention_types_params(_SCREAMING_SNAKE_CASE ) if len(self.attention_layers ) != self.num_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.attention_layers)` == `config.num_layers` """ F"but is `len(config.attention_layers) = {len(self.attention_layers )}`, " F"`config.num_layers = {self.num_layers}`. " """`config.attention_layers` is prepared using `config.attention_types`. """ """Please verify the value of `config.attention_types` argument.""" ) super().__init__(bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @staticmethod def SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : List[str] = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _snake_case ( UpperCamelCase : Union[str, Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Dict ): import torch UpperCAmelCase : Optional[Any] = input.size() UpperCAmelCase : int = len(UpperCamelCase ) UpperCAmelCase : Optional[Any] = shape[dimension] UpperCAmelCase : Union[str, Any] = torch.arange(0 , UpperCamelCase , UpperCamelCase ) UpperCAmelCase : List[Any] = torch.div(sizedim - size , UpperCamelCase , rounding_mode="""floor""" ) + 1 UpperCAmelCase : Optional[Any] = torch.arange(UpperCamelCase ) + low_indices[:min_length][:, None] UpperCAmelCase : List[Any] = [slice(UpperCamelCase )] * rank UpperCAmelCase : Optional[Any] = indices UpperCAmelCase : Optional[Any] = input[s] UpperCAmelCase : List[Any] = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(UpperCamelCase ) def _snake_case ( UpperCamelCase : Tuple , UpperCamelCase : Dict ): import torch UpperCAmelCase : List[str] = torch.arange(1 , UpperCamelCase ) UpperCAmelCase : Any = torch.remainder(UpperCamelCase , UpperCamelCase ) UpperCAmelCase : Union[str, Any] = remainders == 0 UpperCAmelCase : str = candidates[divisor_indices] UpperCAmelCase : Optional[int] = torch.max(UpperCamelCase ) return largest_divisor, torch.div(UpperCamelCase , UpperCamelCase , rounding_mode="""floor""" ) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' UpperCAmelCase : Any = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="""inputs""" ) UpperCAmelCase : str = {0: """batch""", 1: """past_sequence + sequence"""} else: UpperCAmelCase : List[str] = {0: """batch""", 1: """sequence"""} return common_inputs @property def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return self._config.num_heads def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' UpperCAmelCase : List[str] = super(_SCREAMING_SNAKE_CASE , self ).generate_dummy_inputs( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) # We need to order the input in the way they appears in the forward() UpperCAmelCase : Dict = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCAmelCase , UpperCAmelCase : List[Any] = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values UpperCAmelCase : Any = seqlen + 2 UpperCAmelCase : str = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) UpperCAmelCase : Optional[int] = [ (torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) for _ in range(self.num_layers ) ] UpperCAmelCase : List[str] = common_inputs["""attention_mask"""] if self.use_past: UpperCAmelCase : str = ordered_inputs["""attention_mask"""].dtype UpperCAmelCase : int = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE )] , dim=1 ) return ordered_inputs @property def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return 13
359
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __lowerCAmelCase =logging.get_logger(__name__) # pylint: disable=invalid-name __lowerCAmelCase ="\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n" def a ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=8 ) -> List[Any]: """simple docstring""" a_ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a_ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def a ( _UpperCAmelCase , _UpperCAmelCase=5_1_2 , _UpperCAmelCase=5_1_2 ) -> str: """simple docstring""" a_ = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) a_ = np.array(pil_image.convert('RGB' ) ) a_ = arr.astype(np.floataa ) / 1_2_7.5 - 1 a_ = np.transpose(__lowerCamelCase , [2, 0, 1] ) a_ = torch.from_numpy(__lowerCamelCase ).unsqueeze(0 ) return image class _snake_case ( snake_case ): """simple docstring""" def __init__( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) -> Dict: super().__init__() self.register_modules( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , movq=UpperCAmelCase__ , ) a_ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Tuple: a_ = min(int(num_inference_steps * strength ) , UpperCAmelCase__ ) a_ = max(num_inference_steps - init_timestep , 0 ) a_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None ) -> Dict: if not isinstance(UpperCAmelCase__ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase__ )}''' ) a_ = image.to(device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) a_ = batch_size * num_images_per_prompt if image.shape[1] == 4: a_ = image else: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and len(UpperCAmelCase__ ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(UpperCAmelCase__ )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): a_ = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(UpperCAmelCase__ ) ] a_ = torch.cat(UpperCAmelCase__ , dim=0 ) else: a_ = self.movq.encode(UpperCAmelCase__ ).latent_dist.sample(UpperCAmelCase__ ) a_ = self.movq.config.scaling_factor * init_latents a_ = torch.cat([init_latents] , dim=0 ) a_ = init_latents.shape a_ = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) # get latents a_ = self.scheduler.add_noise(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) a_ = init_latents return latents def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__=0 ) -> Tuple: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) a_ = torch.device(F'''cuda:{gpu_id}''' ) a_ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__=0 ) -> Optional[Any]: if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) a_ = torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=UpperCAmelCase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a_ = None for cpu_offloaded_model in [self.unet, self.movq]: a_ = cpu_offload_with_hook(UpperCAmelCase__ , UpperCAmelCase__ , prev_module_hook=UpperCAmelCase__ ) # We'll offload the last model manually. a_ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __SCREAMING_SNAKE_CASE ( self ) -> Tuple: if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase__ ) def __call__( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = 512 , UpperCAmelCase__ = 512 , UpperCAmelCase__ = 100 , UpperCAmelCase__ = 4.0 , UpperCAmelCase__ = 0.3 , UpperCAmelCase__ = 1 , UpperCAmelCase__ = None , UpperCAmelCase__ = "pil" , UpperCAmelCase__ = True , ) -> Any: a_ = self._execution_device a_ = guidance_scale > 1.0 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): a_ = torch.cat(UpperCAmelCase__ , dim=0 ) a_ = image_embeds.shape[0] if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): a_ = torch.cat(UpperCAmelCase__ , dim=0 ) if do_classifier_free_guidance: a_ = image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) a_ = negative_image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) a_ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): a_ = [image] if not all(isinstance(UpperCAmelCase__ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'''Input is in incorrect format: {[type(UpperCAmelCase__ ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) a_ = torch.cat([prepare_image(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) for i in image] , dim=0 ) a_ = image.to(dtype=image_embeds.dtype , device=UpperCAmelCase__ ) a_ = self.movq.encode(UpperCAmelCase__ )['latents'] a_ = latents.repeat_interleave(UpperCAmelCase__ , dim=0 ) self.scheduler.set_timesteps(UpperCAmelCase__ , device=UpperCAmelCase__ ) a_ = self.get_timesteps(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) a_ = timesteps[:1].repeat(batch_size * num_images_per_prompt ) a_ = downscale_height_and_width(UpperCAmelCase__ , UpperCAmelCase__ , self.movq_scale_factor ) a_ = self.prepare_latents( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , image_embeds.dtype , UpperCAmelCase__ , UpperCAmelCase__ ) for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the latents if we are doing classifier free guidance a_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a_ = {'image_embeds': image_embeds} a_ = self.unet( sample=UpperCAmelCase__ , timestep=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , added_cond_kwargs=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] if do_classifier_free_guidance: a_ = noise_pred.split(latents.shape[1] , dim=1 ) a_ = noise_pred.chunk(2 ) a_ = variance_pred.chunk(2 ) a_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a_ = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a_ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a_ = self.scheduler.step( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ , )[0] # post-processing a_ = self.movq.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: a_ = image * 0.5 + 0.5 a_ = image.clamp(0 , 1 ) a_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a_ = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
697
'''simple docstring''' from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowercase =logging.get_logger(__name__) class __magic_name__ ( lowerCAmelCase ): UpperCAmelCase =["audio_values", "audio_mask"] def __init__( self , snake_case=2_0_4_8 , snake_case=1 , snake_case=[1_6, 1_6] , snake_case=1_2_8 , snake_case=4_4_1_0_0 , snake_case=8_6 , snake_case=2_0_4_8 , snake_case=0.0 , **snake_case , ) -> Optional[int]: '''simple docstring''' super().__init__( feature_size=snake_case , sampling_rate=snake_case , padding_value=snake_case , **snake_case , ) _UpperCAmelCase : Dict =spectrogram_length _UpperCAmelCase : Any =num_channels _UpperCAmelCase : Optional[int] =patch_size _UpperCAmelCase : List[str] =feature_size // self.patch_size[1] _UpperCAmelCase : Optional[int] =n_fft _UpperCAmelCase : int =sampling_rate // hop_length_to_sampling_rate _UpperCAmelCase : int =sampling_rate _UpperCAmelCase : List[Any] =padding_value _UpperCAmelCase : Optional[int] =mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=snake_case , min_frequency=0.0 , max_frequency=2_20_50.0 , sampling_rate=snake_case , norm='slaney' , mel_scale='slaney' , ).T def lowerCAmelCase ( self , snake_case) -> np.ndarray: '''simple docstring''' _UpperCAmelCase : Any =spectrogram( snake_case , window_function(self.n_fft , 'hann') , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='dB' , db_range=80.0 , ) _UpperCAmelCase : Any =log_spec[:, :-1] _UpperCAmelCase : List[str] =log_spec - 20.0 _UpperCAmelCase : Union[str, Any] =np.clip(log_spec / 40.0 , -2.0 , 0.0) + 1.0 return log_spec def __call__( self , snake_case , snake_case = None , snake_case = True , snake_case = None , snake_case = False , snake_case = False , **snake_case , ) -> BatchFeature: '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( 'This feature extractor is set to support sampling rate' f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled" f" with {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.') _UpperCAmelCase : Tuple =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}") _UpperCAmelCase : str =is_batched_numpy or ( isinstance(snake_case , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list))) ) if is_batched: _UpperCAmelCase : List[str] =[np.asarray([speech] , dtype=np.floataa).T for speech in raw_speech] elif not is_batched and not isinstance(snake_case , np.ndarray): _UpperCAmelCase : List[Any] =np.asarray(snake_case , dtype=np.floataa) elif isinstance(snake_case , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa): _UpperCAmelCase : List[Any] =raw_speech.astype(np.floataa) # always return batch if not is_batched: _UpperCAmelCase : Dict =[np.asarray([raw_speech]).T] # Convert audio signals to log mel spectrograms, truncate by time axis _UpperCAmelCase : List[Any] =[ self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , snake_case): _UpperCAmelCase : Dict =[np.asarray(snake_case , dtype=np.floataa) for feature in audio_features] # Create audio attention mask _UpperCAmelCase : Tuple =max( [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features]) # The maximum number of audio patches in a batch if return_attention_mask: _UpperCAmelCase : Any =[ (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0] for feature in audio_features ] _UpperCAmelCase : int =np.array(snake_case).astype(np.floataa) # convert into correct format for padding _UpperCAmelCase : List[Any] =max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch _UpperCAmelCase : List[str] =np.ones([len(snake_case), 1, max_time_len, self.feature_size]).astype(np.floataa) _UpperCAmelCase : Any =padded_audio_features * self.padding_value for i in range(len(snake_case)): _UpperCAmelCase : List[str] =audio_features[i] _UpperCAmelCase : Dict =feature # return as BatchFeature if return_attention_mask: _UpperCAmelCase : List[str] ={'audio_values': padded_audio_features, 'audio_mask': audio_mask} else: _UpperCAmelCase : Optional[int] ={'audio_values': padded_audio_features} _UpperCAmelCase : Any =BatchFeature(data=snake_case , tensor_type=snake_case) return encoded_inputs
446
0
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class lowercase ( unittest.TestCase ): def A__ ( self): lowercase = inspect.getfile(accelerate.test_utils) lowercase = os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ['''scripts''', '''external_deps''', '''test_metrics.py''']) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 lowercase = test_metrics @require_cpu def A__ ( self): debug_launcher(self.test_metrics.main ,num_processes=1) @require_cpu def A__ ( self): debug_launcher(self.test_metrics.main) @require_single_gpu def A__ ( self): self.test_metrics.main() @require_multi_gpu def A__ ( self): print(f'Found {torch.cuda.device_count()} devices.') lowercase = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ ,env=os.environ.copy())
716
# Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file lowercase__ :Any = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def UpperCamelCase ( lowerCAmelCase__=None ): '''simple docstring''' if subparsers is not None: lowercase = subparsers.add_parser('''tpu-config''' , description=_description ) else: lowercase = argparse.ArgumentParser('''Accelerate tpu-config command''' , description=_description ) # Core arguments lowercase = parser.add_argument_group( '''Config Arguments''' , '''Arguments that can be configured through `accelerate config`.''' ) config_args.add_argument( '''--config_file''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''Path to the config file to use for accelerate.''' , ) config_args.add_argument( '''--tpu_name''' , default=lowerCAmelCase__ , help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''' , ) config_args.add_argument( '''--tpu_zone''' , default=lowerCAmelCase__ , help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''' , ) lowercase = parser.add_argument_group('''TPU Arguments''' , '''Arguments for options ran inside the TPU.''' ) pod_args.add_argument( '''--use_alpha''' , action='''store_true''' , help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''' , ) pod_args.add_argument( '''--command_file''' , default=lowerCAmelCase__ , help='''The path to the file containing the commands to run on the pod on startup.''' , ) pod_args.add_argument( '''--command''' , action='''append''' , nargs='''+''' , help='''A command to run on the pod. Can be passed multiple times.''' , ) pod_args.add_argument( '''--install_accelerate''' , action='''store_true''' , help='''Whether to install accelerate on the pod. Defaults to False.''' , ) pod_args.add_argument( '''--accelerate_version''' , default='''latest''' , help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''' , ) pod_args.add_argument( '''--debug''' , action='''store_true''' , help='''If set, will print the command that would be run instead of running it.''' ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase__ ) return parser def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(lowerCAmelCase__ ): lowercase = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: lowercase = defaults.command_file if not args.command and defaults.commands is not None: lowercase = defaults.commands if not args.tpu_name: lowercase = defaults.tpu_name if not args.tpu_zone: lowercase = defaults.tpu_zone if args.accelerate_version == "dev": lowercase = '''git+https://github.com/huggingface/accelerate.git''' elif args.accelerate_version == "latest": lowercase = '''accelerate -U''' elif isinstance(parse(args.accelerate_version ) , lowerCAmelCase__ ): lowercase = f'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('''You must specify either a command file or a command to run on the pod.''' ) if args.command_file: with open(args.command_file , '''r''' ) as f: lowercase = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , lowerCAmelCase__ ): lowercase = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate lowercase = ['''cd /usr/share'''] if args.install_accelerate: new_cmd += [f'pip install {args.accelerate_version}'] new_cmd += args.command lowercase = '''; '''.join(lowerCAmelCase__ ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess lowercase = ['''gcloud'''] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f'Running {" ".join(lowerCAmelCase__ )}' ) return subprocess.run(lowerCAmelCase__ ) print('''Successfully setup pod.''' ) def UpperCamelCase ( ): '''simple docstring''' lowercase = tpu_command_parser() lowercase = parser.parse_args() tpu_command_launcher(lowerCAmelCase__ )
633
0
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase : Tuple = logging.get_logger(__name__) UpperCamelCase : str = { """kakaobrain/align-base""": """https://huggingface.co/kakaobrain/align-base/resolve/main/config.json""", } class A__ ( A__ ): """simple docstring""" _lowercase = 'align_text_model' def __init__( self : Dict , lowerCamelCase__ : Dict=30_522 , lowerCamelCase__ : Optional[int]=768 , lowerCamelCase__ : Tuple=12 , lowerCamelCase__ : Tuple=12 , lowerCamelCase__ : List[str]=3_072 , lowerCamelCase__ : Union[str, Any]="gelu" , lowerCamelCase__ : str=0.1 , lowerCamelCase__ : List[Any]=0.1 , lowerCamelCase__ : Any=512 , lowerCamelCase__ : Optional[int]=2 , lowerCamelCase__ : Optional[int]=0.02 , lowerCamelCase__ : Optional[Any]=1E-12 , lowerCamelCase__ : Dict=0 , lowerCamelCase__ : Optional[int]="absolute" , lowerCamelCase__ : List[Any]=True , **lowerCamelCase__ : Optional[Any] , ): super().__init__(**lowerCamelCase__ ) a__ : Optional[Any] = vocab_size a__ : Optional[int] = hidden_size a__ : str = num_hidden_layers a__ : int = num_attention_heads a__ : Any = hidden_act a__ : str = intermediate_size a__ : List[Any] = hidden_dropout_prob a__ : str = attention_probs_dropout_prob a__ : List[Any] = max_position_embeddings a__ : List[Any] = type_vocab_size a__ : Optional[int] = initializer_range a__ : int = layer_norm_eps a__ : Optional[Any] = position_embedding_type a__ : Dict = use_cache a__ : Optional[int] = pad_token_id @classmethod def _UpperCamelCase( cls : int , lowerCamelCase__ : Union[str, os.PathLike] , **lowerCamelCase__ : List[str] ): cls._set_token_in_kwargs(lowerCamelCase__ ) a__, a__ : Dict = cls.get_config_dict(lowerCamelCase__ , **lowerCamelCase__ ) # get the text config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": a__ : int = config_dict["text_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(lowerCamelCase__ , **lowerCamelCase__ ) class A__ ( A__ ): """simple docstring""" _lowercase = 'align_vision_model' def __init__( self : List[Any] , lowerCamelCase__ : int = 3 , lowerCamelCase__ : int = 600 , lowerCamelCase__ : float = 2.0 , lowerCamelCase__ : float = 3.1 , lowerCamelCase__ : int = 8 , lowerCamelCase__ : List[int] = [3, 3, 5, 3, 5, 5, 3] , lowerCamelCase__ : List[int] = [32, 16, 24, 40, 80, 112, 192] , lowerCamelCase__ : List[int] = [16, 24, 40, 80, 112, 192, 320] , lowerCamelCase__ : List[int] = [] , lowerCamelCase__ : List[int] = [1, 2, 2, 2, 1, 2, 1] , lowerCamelCase__ : List[int] = [1, 2, 2, 3, 3, 4, 1] , lowerCamelCase__ : List[int] = [1, 6, 6, 6, 6, 6, 6] , lowerCamelCase__ : float = 0.25 , lowerCamelCase__ : str = "swish" , lowerCamelCase__ : int = 2_560 , lowerCamelCase__ : str = "mean" , lowerCamelCase__ : float = 0.02 , lowerCamelCase__ : float = 0.001 , lowerCamelCase__ : float = 0.99 , lowerCamelCase__ : float = 0.2 , **lowerCamelCase__ : List[str] , ): super().__init__(**lowerCamelCase__ ) a__ : Union[str, Any] = num_channels a__ : List[Any] = image_size a__ : int = width_coefficient a__ : int = depth_coefficient a__ : Union[str, Any] = depth_divisor a__ : Optional[Any] = kernel_sizes a__ : Union[str, Any] = in_channels a__ : Optional[Any] = out_channels a__ : Any = depthwise_padding a__ : Any = strides a__ : int = num_block_repeats a__ : List[Any] = expand_ratios a__ : int = squeeze_expansion_ratio a__ : Optional[Any] = hidden_act a__ : List[str] = hidden_dim a__ : List[str] = pooling_type a__ : List[str] = initializer_range a__ : Union[str, Any] = batch_norm_eps a__ : int = batch_norm_momentum a__ : List[str] = drop_connect_rate a__ : Dict = sum(lowerCamelCase__ ) * 4 @classmethod def _UpperCamelCase( cls : Dict , lowerCamelCase__ : Union[str, os.PathLike] , **lowerCamelCase__ : Dict ): cls._set_token_in_kwargs(lowerCamelCase__ ) a__, a__ : Union[str, Any] = cls.get_config_dict(lowerCamelCase__ , **lowerCamelCase__ ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": a__ : List[str] = 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(lowerCamelCase__ , **lowerCamelCase__ ) class A__ ( A__ ): """simple docstring""" _lowercase = 'align' _lowercase = True def __init__( self : str , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : Any=None , lowerCamelCase__ : Dict=640 , lowerCamelCase__ : Tuple=1.0 , lowerCamelCase__ : Any=0.02 , **lowerCamelCase__ : Optional[int] , ): super().__init__(**lowerCamelCase__ ) if text_config is None: a__ : Optional[int] = {} logger.info("text_config is None. Initializing the AlignTextConfig with default values." ) if vision_config is None: a__ : Union[str, Any] = {} logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." ) a__ : Optional[Any] = AlignTextConfig(**lowerCamelCase__ ) a__ : str = AlignVisionConfig(**lowerCamelCase__ ) a__ : Dict = projection_dim a__ : List[str] = temperature_init_value a__ : Dict = initializer_range @classmethod def _UpperCamelCase( cls : Tuple , lowerCamelCase__ : AlignTextConfig , lowerCamelCase__ : AlignVisionConfig , **lowerCamelCase__ : List[str] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowerCamelCase__ ) def _UpperCamelCase( self : Any ): a__ : int = copy.deepcopy(self.__dict__ ) a__ : int = self.text_config.to_dict() a__ : Tuple = self.vision_config.to_dict() a__ : Optional[Any] = self.__class__.model_type return output
37
"""simple docstring""" import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class UpperCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): @register_to_config def __init__( self , snake_case__ = 128 , snake_case__ = 256 , snake_case__ = 2_000.0 , snake_case__ = 768 , snake_case__ = 12 , snake_case__ = 12 , snake_case__ = 64 , snake_case__ = 2048 , snake_case__ = 0.1 , ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : List[str] = nn.Sequential( nn.Linear(snake_case__ , d_model * 4 , bias=snake_case__ ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=snake_case__ ) , nn.SiLU() , ) _SCREAMING_SNAKE_CASE : Dict = nn.Embedding(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE : str = False _SCREAMING_SNAKE_CASE : Optional[int] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Dropout(p=snake_case__ ) _SCREAMING_SNAKE_CASE : Tuple = nn.ModuleList() for lyr_num in range(snake_case__ ): # FiLM conditional T5 decoder _SCREAMING_SNAKE_CASE : Union[str, Any] = DecoderLayer(d_model=snake_case__ , d_kv=snake_case__ , num_heads=snake_case__ , d_ff=snake_case__ , dropout_rate=snake_case__ ) self.decoders.append(snake_case__ ) _SCREAMING_SNAKE_CASE : str = TaLayerNorm(snake_case__ ) _SCREAMING_SNAKE_CASE : str = nn.Dropout(p=snake_case__ ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. _SCREAMING_SNAKE_CASE : List[str] = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) _SCREAMING_SNAKE_CASE : str = self.conditioning_emb(snake_case__ ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) _SCREAMING_SNAKE_CASE : Any = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. _SCREAMING_SNAKE_CASE : List[Any] = torch.broadcast_to( torch.arange(snake_case__ , device=decoder_input_tokens.device ) , (batch, seq_length) , ) _SCREAMING_SNAKE_CASE : Any = self.position_encoding(snake_case__ ) _SCREAMING_SNAKE_CASE : Any = self.continuous_inputs_projection(snake_case__ ) inputs += position_encodings _SCREAMING_SNAKE_CASE : Tuple = self.dropout(snake_case__ ) # decoder: No padding present. _SCREAMING_SNAKE_CASE : Union[str, Any] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. _SCREAMING_SNAKE_CASE : Any = [(x, self.encoder_decoder_mask(snake_case__ , snake_case__ )) for x, y in encodings_and_masks] # cross attend style: concat encodings _SCREAMING_SNAKE_CASE : int = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: _SCREAMING_SNAKE_CASE : Any = lyr( snake_case__ , conditioning_emb=snake_case__ , encoder_hidden_states=snake_case__ , encoder_attention_mask=snake_case__ , )[0] _SCREAMING_SNAKE_CASE : Tuple = self.decoder_norm(snake_case__ ) _SCREAMING_SNAKE_CASE : Dict = self.post_dropout(snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[int] = self.spec_out(snake_case__ ) return spec_out class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=1E-6 ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=snake_case__ , d_kv=snake_case__ , num_heads=snake_case__ , dropout_rate=snake_case__ ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=snake_case__ , d_kv=snake_case__ , num_heads=snake_case__ , dropout_rate=snake_case__ , layer_norm_epsilon=snake_case__ , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=snake_case__ , d_ff=snake_case__ , dropout_rate=snake_case__ , layer_norm_epsilon=snake_case__ ) ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__=None , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[int] = self.layer[0]( snake_case__ , conditioning_emb=snake_case__ , attention_mask=snake_case__ , ) if encoder_hidden_states is not None: _SCREAMING_SNAKE_CASE : Tuple = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) _SCREAMING_SNAKE_CASE : int = self.layer[1]( snake_case__ , key_value_states=snake_case__ , attention_mask=snake_case__ , ) # Apply Film Conditional Feed Forward layer _SCREAMING_SNAKE_CASE : Union[str, Any] = self.layer[-1](snake_case__ , snake_case__ ) return (hidden_states,) class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : List[str] = TaLayerNorm(snake_case__ ) _SCREAMING_SNAKE_CASE : int = TaFiLMLayer(in_features=d_model * 4 , out_features=snake_case__ ) _SCREAMING_SNAKE_CASE : str = Attention(query_dim=snake_case__ , heads=snake_case__ , dim_head=snake_case__ , out_bias=snake_case__ , scale_qk=snake_case__ ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Dropout(snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__=None , snake_case__=None , ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[Any] = self.layer_norm(snake_case__ ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : int = self.FiLMLayer(snake_case__ , snake_case__ ) # Self-attention block _SCREAMING_SNAKE_CASE : Tuple = self.attention(snake_case__ ) _SCREAMING_SNAKE_CASE : str = hidden_states + self.dropout(snake_case__ ) return hidden_states class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = Attention(query_dim=snake_case__ , heads=snake_case__ , dim_head=snake_case__ , out_bias=snake_case__ , scale_qk=snake_case__ ) _SCREAMING_SNAKE_CASE : int = TaLayerNorm(snake_case__ , eps=snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Dropout(snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__=None , snake_case__=None , ): """simple docstring""" _SCREAMING_SNAKE_CASE : Dict = self.layer_norm(snake_case__ ) _SCREAMING_SNAKE_CASE : int = self.attention( snake_case__ , encoder_hidden_states=snake_case__ , attention_mask=attention_mask.squeeze(1 ) , ) _SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.dropout(snake_case__ ) return layer_output class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Tuple = TaDenseGatedActDense(d_model=snake_case__ , d_ff=snake_case__ , dropout_rate=snake_case__ ) _SCREAMING_SNAKE_CASE : List[Any] = TaFiLMLayer(in_features=d_model * 4 , out_features=snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = TaLayerNorm(snake_case__ , eps=snake_case__ ) _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Dropout(snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__=None ): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = self.layer_norm(snake_case__ ) if conditioning_emb is not None: _SCREAMING_SNAKE_CASE : Dict = self.film(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE : Tuple = self.DenseReluDense(snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[int] = hidden_states + self.dropout(snake_case__ ) return hidden_states class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _SCREAMING_SNAKE_CASE : str = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _SCREAMING_SNAKE_CASE : Any = nn.Linear(snake_case__ , snake_case__ , bias=snake_case__ ) _SCREAMING_SNAKE_CASE : List[Any] = nn.Dropout(snake_case__ ) _SCREAMING_SNAKE_CASE : Tuple = NewGELUActivation() def __SCREAMING_SNAKE_CASE ( self , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : int = self.act(self.wi_a(snake_case__ ) ) _SCREAMING_SNAKE_CASE : Tuple = self.wi_a(snake_case__ ) _SCREAMING_SNAKE_CASE : Dict = hidden_gelu * hidden_linear _SCREAMING_SNAKE_CASE : Dict = self.dropout(snake_case__ ) _SCREAMING_SNAKE_CASE : int = self.wo(snake_case__ ) return hidden_states class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__=1E-6 ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.ones(snake_case__ ) ) _SCREAMING_SNAKE_CASE : Dict = eps def __SCREAMING_SNAKE_CASE ( self , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=snake_case__ ) _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: _SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class UpperCamelCase ( nn.Module ): def __SCREAMING_SNAKE_CASE ( self , snake_case__ ): """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044_715 * torch.pow(snake_case__ , 3.0 )) )) class UpperCamelCase ( nn.Module ): def __init__( self , snake_case__ , snake_case__ ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE : Optional[int] = nn.Linear(snake_case__ , out_features * 2 , bias=snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ , snake_case__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : Optional[Any] = self.scale_bias(snake_case__ ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = torch.chunk(snake_case__ , 2 , -1 ) _SCREAMING_SNAKE_CASE : Dict = x * (1 + scale) + shift return x
572
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class __a : '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = MBartConfig _SCREAMING_SNAKE_CASE :int = {} _SCREAMING_SNAKE_CASE :int = """gelu""" def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Any = seq_length SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : Optional[Any] = use_labels SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : str = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = eos_token_id SCREAMING_SNAKE_CASE__ : int = pad_token_id SCREAMING_SNAKE_CASE__ : List[Any] = bos_token_id def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE__ : str = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Any = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) SCREAMING_SNAKE_CASE__ : int = prepare_mbart_inputs_dict(_a , _a , _a ) return config, inputs_dict def _a ( self , _a , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = TFMBartModel(config=_a ).get_decoder() SCREAMING_SNAKE_CASE__ : Tuple = inputs_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ : Any = input_ids[:1, :] SCREAMING_SNAKE_CASE__ : int = inputs_dict["""attention_mask"""][:1, :] SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict["""head_mask"""] SCREAMING_SNAKE_CASE__ : Any = 1 # first forward pass SCREAMING_SNAKE_CASE__ : Optional[Any] = model(_a , attention_mask=_a , head_mask=_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : int = outputs.to_tuple() SCREAMING_SNAKE_CASE__ : str = past_key_values[1] def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , ) -> Any: if attention_mask is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.cast(tf.math.not_equal(__lowerCAmelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __a (UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () _SCREAMING_SNAKE_CASE :List[Any] = (TFMBartForConditionalGeneration,) if is_tf_available() else () _SCREAMING_SNAKE_CASE :Optional[int] = ( { """conversational""": TFMBartForConditionalGeneration, """feature-extraction""": TFMBartModel, """summarization""": TFMBartForConditionalGeneration, """text2text-generation""": TFMBartForConditionalGeneration, """translation""": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE :str = True _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :Optional[Any] = False def _a ( self , _a , _a , _a , _a , _a ) -> Dict: """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFMBartModelTester(self ) SCREAMING_SNAKE_CASE__ : Dict = ConfigTester(self , config_class=_a ) def _a ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) @require_sentencepiece @require_tokenizers @require_tf class __a (unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = [ """ UN Chief Says There Is No Military Solution in Syria""", ] _SCREAMING_SNAKE_CASE :str = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", ] _SCREAMING_SNAKE_CASE :Optional[int] = """facebook/mbart-large-en-ro""" @cached_property def _a ( self ) -> str: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_a ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.translate_src_text(**_a ) self.assertListEqual(self.expected_text , _a ) def _a ( self , **_a ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer(self.src_text , **_a , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer.batch_decode(_a , skip_special_tokens=_a ) return generated_words @slow def _a ( self ) -> Union[str, Any]: """simple docstring""" self._assert_generated_batch_equal_expected()
718
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __a : '''simple docstring''' def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length SCREAMING_SNAKE_CASE__ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask SCREAMING_SNAKE_CASE__ : List[str] = use_labels SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = d_ff SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : str = decoder_layers def _a ( self ) -> Tuple: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any: """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config() SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a ) return config, input_dict def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() return config, inputs_dict def _a ( self ) -> List[str]: """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self ) -> List[Any]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a ) model.to(_a ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model( input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(_a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval() # first forward pass SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a ) SCREAMING_SNAKE_CASE__ : str = model(_a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a ) self.parent.assertTrue(len(_a ) == len(_a ) ) self.parent.assertTrue(len(_a ) == len(_a ) + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) ) def _a ( self , _a , _a , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(_a ).any().item() ) @require_torch class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else () _SCREAMING_SNAKE_CASE :List[str] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE :Union[str, Any] = True _SCREAMING_SNAKE_CASE :Tuple = False _SCREAMING_SNAKE_CASE :Optional[Any] = False _SCREAMING_SNAKE_CASE :List[Any] = True _SCREAMING_SNAKE_CASE :List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9] def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def _a ( self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_a ) def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0] SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval() model.to(_a ) SCREAMING_SNAKE_CASE__ : List[str] = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ), } for attn_name, (name, mask) in zip(_a , head_masking.items() ): SCREAMING_SNAKE_CASE__ : List[str] = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": SCREAMING_SNAKE_CASE__ : str = torch.ones( config.num_decoder_layers , config.num_heads , device=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def _a ( self ) -> Dict: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class __a (unittest.TestCase): '''simple docstring''' @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(_a , _a ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) ) SCREAMING_SNAKE_CASE__ : int = [ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a ) self.assertEqual(_a , _a )
12
0
"""simple docstring""" import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A ( SCREAMING_SNAKE_CASE_ ,unittest.TestCase ): UpperCAmelCase__ = RobertaTokenizer UpperCAmelCase__ = RobertaTokenizerFast UpperCAmelCase__ = True UpperCAmelCase__ = {"cls_token": "<s>"} def lowerCamelCase__ ( self : List[str] ) -> Dict: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __magic_name__: List[Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __magic_name__: List[str] = dict(zip(__snake_case , range(len(__snake_case ) ) ) ) __magic_name__: Tuple = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __magic_name__: Optional[int] = {"""unk_token""": """<unk>"""} __magic_name__: List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __magic_name__: int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__snake_case ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__snake_case ) ) def lowerCamelCase__ ( self : Optional[Any] , **__snake_case : str ) -> str: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__snake_case ) def lowerCamelCase__ ( self : Any , **__snake_case : Optional[Any] ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **__snake_case ) def lowerCamelCase__ ( self : List[str] , __snake_case : Optional[Any] ) -> List[Any]: __magic_name__: List[str] = """lower newer""" __magic_name__: Optional[int] = """lower newer""" return input_text, output_text def lowerCamelCase__ ( self : List[str] ) -> Optional[Any]: __magic_name__: List[str] = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) __magic_name__: List[Any] = """lower newer""" __magic_name__: List[str] = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] __magic_name__: Optional[int] = tokenizer.tokenize(__snake_case ) # , add_prefix_space=True) self.assertListEqual(__snake_case , __snake_case ) __magic_name__: int = tokens + [tokenizer.unk_token] __magic_name__: Tuple = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , __snake_case ) def lowerCamelCase__ ( self : List[str] ) -> Optional[int]: __magic_name__: int = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=__snake_case ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=__snake_case ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2] , ) @slow def lowerCamelCase__ ( self : Any ) -> List[str]: __magic_name__: Any = self.tokenizer_class.from_pretrained("""roberta-base""" ) __magic_name__: List[str] = tokenizer.encode("""sequence builders""" , add_special_tokens=__snake_case ) __magic_name__: Union[str, Any] = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__snake_case ) __magic_name__: Optional[Any] = tokenizer.encode( """sequence builders""" , add_special_tokens=__snake_case , add_prefix_space=__snake_case ) __magic_name__: List[str] = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__snake_case , add_prefix_space=__snake_case ) __magic_name__: Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__snake_case ) __magic_name__: Optional[Any] = tokenizer.build_inputs_with_special_tokens(__snake_case , __snake_case ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def lowerCamelCase__ ( self : int ) -> str: __magic_name__: int = self.get_tokenizer() __magic_name__: Tuple = """Encode this sequence.""" __magic_name__: List[str] = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments __magic_name__: Optional[Any] = tokenizer.encode(__snake_case , add_special_tokens=__snake_case , add_prefix_space=__snake_case ) __magic_name__: Optional[Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__snake_case , __snake_case ) __magic_name__: Union[str, Any] = tokenizer.encode(__snake_case , add_special_tokens=__snake_case , add_prefix_space=__snake_case ) __magic_name__: Optional[Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__snake_case , __snake_case ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) __magic_name__: Union[str, Any] = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) __magic_name__: Optional[Any] = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__snake_case , __snake_case ) # Testing spaces after special tokens __magic_name__: List[str] = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case )} ) # mask token has a left space __magic_name__: int = tokenizer.convert_tokens_to_ids(__snake_case ) __magic_name__: int = """Encode <mask> sequence""" __magic_name__: List[Any] = """Encode <mask>sequence""" __magic_name__: Union[str, Any] = tokenizer.encode(__snake_case ) __magic_name__: Optional[Any] = encoded.index(__snake_case ) __magic_name__: Tuple = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__snake_case , __snake_case ) __magic_name__: List[str] = tokenizer.encode(__snake_case ) __magic_name__: Any = encoded.index(__snake_case ) __magic_name__: str = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__snake_case , __snake_case ) def lowerCamelCase__ ( self : str ) -> int: pass def lowerCamelCase__ ( self : str ) -> Tuple: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __magic_name__: Tuple = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) __magic_name__: List[Any] = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) __magic_name__: List[Any] = """A, <mask> AllenNLP sentence.""" __magic_name__: Optional[Any] = tokenizer_r.encode_plus(__snake_case , add_special_tokens=__snake_case , return_token_type_ids=__snake_case ) __magic_name__: str = tokenizer_p.encode_plus(__snake_case , add_special_tokens=__snake_case , return_token_type_ids=__snake_case ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) __magic_name__: List[str] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) __magic_name__: List[Any] = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( __snake_case , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __snake_case , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def lowerCamelCase__ ( self : Tuple ) -> str: for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): __magic_name__: Union[str, Any] = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: Any = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) __magic_name__: Any = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , __snake_case ) self.assertEqual(post_processor_state["""add_prefix_space"""] , __snake_case ) self.assertEqual(post_processor_state["""trim_offsets"""] , __snake_case ) def lowerCamelCase__ ( self : Any ) -> Tuple: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __magic_name__: List[Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` __magic_name__: Union[str, Any] = F'{text_of_1_token} {text_of_1_token}' __magic_name__: Dict = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: Union[str, Any] = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__snake_case ) + 1, len(__snake_case ) + 1 + len(__snake_case )) , ) __magic_name__: Union[str, Any] = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: str = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__snake_case ) + 1, len(__snake_case ) + 1 + len(__snake_case )) , ) __magic_name__: List[str] = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: Any = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__snake_case ), len(__snake_case ) + 1 + len(__snake_case )) , ) __magic_name__: int = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: Dict = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__snake_case ), len(__snake_case ) + 1 + len(__snake_case )) , ) __magic_name__: Dict = F' {text}' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) __magic_name__: str = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: Any = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__snake_case ) + 1, 1 + len(__snake_case ) + 1 + len(__snake_case )) , ) __magic_name__: int = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: str = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__snake_case ), 1 + len(__snake_case ) + 1 + len(__snake_case )) , ) __magic_name__: List[Any] = self.rust_tokenizer_class.from_pretrained( __snake_case , use_fast=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case ) __magic_name__: Union[str, Any] = tokenizer_r(__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__snake_case )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__snake_case ), 1 + len(__snake_case ) + 1 + len(__snake_case )) , )
96
'''simple docstring''' import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""): __a: Optional[Any] = True from torch.cuda.amp import autocast __a: Optional[Any] = logging.getLogger(__name__) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "Whether to log verbose messages or not."} , ) SCREAMING_SNAKE_CASE = field( default=2.0 , metadata={"help": "Maximum temperature for gumbel softmax."} ) SCREAMING_SNAKE_CASE = field( default=0.5 , metadata={"help": "Minimum temperature for gumbel softmax."} ) SCREAMING_SNAKE_CASE = field( default=0.999995 , metadata={"help": "Decay of gumbel temperature during training."} ) def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) lowercase__ : int = logging.WARNING if model_args.verbose_logging: lowercase__ : str = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): lowercase__ : List[Any] = logging.INFO logger.setLevel(UpperCAmelCase ) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) SCREAMING_SNAKE_CASE = field( default="validation" , metadata={ "help": ( "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) SCREAMING_SNAKE_CASE = field( default="file" , metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"} , ) SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) SCREAMING_SNAKE_CASE = field( default=1 , metadata={ "help": "The percentage of the train set used as validation set in case there's no validation split" } , ) SCREAMING_SNAKE_CASE = field( default=a__ , metadata={"help": "The number of processes to use for the preprocessing."} , ) SCREAMING_SNAKE_CASE = field( default=20.0 , metadata={"help": "Filter audio files that are longer than `max_duration_in_seconds` seconds"} ) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = "longest" SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def __call__( self , __lowerCAmelCase ) -> Dict[str, torch.Tensor]: # reformat list to dict and set to pytorch format lowercase__ : List[str] = self.feature_extractor.pad( __lowerCAmelCase , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) lowercase__ : List[str] = self.model._get_feat_extract_output_lengths(batch['''input_values'''].shape[-1] ) lowercase__ : Optional[Any] = batch['''input_values'''].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula lowercase__ : str = self.model._get_feat_extract_output_lengths(batch['''attention_mask'''].sum(-1 ) ).to( torch.long ) lowercase__ : int = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['''input_values'''].device ) # these two operations makes sure that all values # before the output lengths indices are attended to lowercase__ : Any = 1 lowercase__ : Dict = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices lowercase__ : List[Any] = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=__lowerCAmelCase , min_masks=2 , ) return batch class UpperCAmelCase ( a__ ): '''simple docstring''' def __init__( self , *__lowerCAmelCase , __lowerCAmelCase=1 , __lowerCAmelCase=0 , __lowerCAmelCase=1.0 , **__lowerCAmelCase ) -> int: super().__init__(*__lowerCAmelCase , **__lowerCAmelCase ) lowercase__ : Union[str, Any] = 0 lowercase__ : List[str] = max_gumbel_temp lowercase__ : Union[str, Any] = min_gumbel_temp lowercase__ : List[Any] = gumbel_temp_decay def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase ) -> torch.Tensor: model.train() lowercase__ : List[Any] = self._prepare_inputs(__lowerCAmelCase ) if self.use_amp: with autocast(): lowercase__ : List[Any] = self.compute_loss(__lowerCAmelCase , __lowerCAmelCase ) else: lowercase__ : Optional[Any] = self.compute_loss(__lowerCAmelCase , __lowerCAmelCase ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": lowercase__ : str = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowercase__ : Union[str, Any] = loss.sum() / (inputs['''mask_time_indices''']).sum() else: raise ValueError(F"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: lowercase__ : str = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__lowerCAmelCase ).backward() elif self.use_apex: with amp.scale_loss(__lowerCAmelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__lowerCAmelCase ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def __UpperCamelCase ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowercase__ : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase__ , lowercase__ , lowercase__ : Dict = parser.parse_args_into_dataclasses() configure_logger(UpperCAmelCase , UpperCAmelCase ) # Downloading and loading a dataset from the hub. lowercase__ : Union[str, Any] = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" lowercase__ : Dict = DatasetDict() lowercase__ : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""{data_args.train_split_name}[:{data_args.validation_split_percentage}%]""" , cache_dir=model_args.cache_dir , ) lowercase__ : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""{data_args.train_split_name}[{data_args.validation_split_percentage}%:]""" , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" lowercase__ : Any = DatasetDict() lowercase__ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='''validation''' , cache_dir=model_args.cache_dir , ) lowercase__ : str = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""{data_args.train_split_name}""" , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported lowercase__ : Optional[int] = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=UpperCAmelCase ) def prepare_dataset(UpperCAmelCase ): # check that all files have the correct sampling rate lowercase__ , lowercase__ : int = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays lowercase__ : int = datasets.map( UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['''train'''].column_names ) # filter audio files that are too long lowercase__ : List[Any] = vectorized_datasets.filter( lambda UpperCAmelCase : len(data['''speech'''] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(UpperCAmelCase ): return feature_extractor(batch['''speech'''] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` lowercase__ : Tuple = vectorized_datasets.map( UpperCAmelCase , batched=UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['''train'''].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 lowercase__ : Union[str, Any] = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( '''PreTraining is only supported for ``config.do_stable_layer_norm=True`` and''' ''' ``config.feat_extract_norm=\'layer\'''' ) lowercase__ : int = WavaVecaForPreTraining(UpperCAmelCase ) lowercase__ : List[Any] = DataCollatorForWavaVecaPretraining(model=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowercase__ : Any = WavaVecaPreTrainer( model=UpperCAmelCase , data_collator=UpperCAmelCase , args=UpperCAmelCase , train_dataset=vectorized_datasets['''train'''] , eval_dataset=vectorized_datasets['''validation'''] , tokenizer=UpperCAmelCase , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
152
0
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase = pytest.mark.integration UpperCAmelCase = {"""comet"""} UpperCAmelCase = importlib.util.find_spec("""fairseq""") is not None UpperCAmelCase = {"""code_eval"""} UpperCAmelCase = os.name == """nt""" UpperCAmelCase = {"""bertscore""", """frugalscore""", """perplexity"""} UpperCAmelCase = importlib.util.find_spec("""transformers""") is not None def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Optional[int]: """simple docstring""" @wraps(SCREAMING_SNAKE_CASE ) def wrapper(self , SCREAMING_SNAKE_CASE ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('''"test requires Fairseq"''' ) else: test_case(self , SCREAMING_SNAKE_CASE ) return wrapper def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> List[Any]: """simple docstring""" @wraps(SCREAMING_SNAKE_CASE ) def wrapper(self , SCREAMING_SNAKE_CASE ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('''"test requires transformers"''' ) else: test_case(self , SCREAMING_SNAKE_CASE ) return wrapper def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> List[str]: """simple docstring""" @wraps(SCREAMING_SNAKE_CASE ) def wrapper(self , SCREAMING_SNAKE_CASE ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('''"test not supported on Windows"''' ) else: test_case(self , SCREAMING_SNAKE_CASE ) return wrapper def __lowerCAmelCase ()-> int: """simple docstring""" snake_case_ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) @local class lowerCAmelCase_ ( parameterized.TestCase ): '''simple docstring''' __snake_case = {} __snake_case = None @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' ) def UpperCamelCase__ ( self , _UpperCAmelCase ): snake_case_ = '''[...]''' snake_case_ = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , _UpperCAmelCase ) ).module_path ) snake_case_ = datasets.load.import_main_class(metric_module.__name__ , dataset=_UpperCAmelCase ) # check parameters snake_case_ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(_UpperCAmelCase , metric_module.__name__ ): with self.use_local_metrics(): try: snake_case_ = doctest.testmod(_UpperCAmelCase , verbose=_UpperCAmelCase , raise_on_error=_UpperCAmelCase ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def UpperCamelCase__ ( self , _UpperCAmelCase ): snake_case_ = '''[...]''' snake_case_ = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , _UpperCAmelCase ) ).module_path ) # run doctest with self.use_local_metrics(): snake_case_ = doctest.testmod(_UpperCAmelCase , verbose=_UpperCAmelCase , raise_on_error=_UpperCAmelCase ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase ): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](_UpperCAmelCase ): yield else: yield @contextmanager def UpperCamelCase__ ( self ): def load_local_metric(_UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase ): return load_metric(os.path.join('''metrics''' , _UpperCAmelCase ) , *_UpperCAmelCase , **_UpperCAmelCase ) with patch('''datasets.load_metric''' ) as mock_load_metric: snake_case_ = load_local_metric yield @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase ): def wrapper(_UpperCAmelCase ): snake_case_ = contextmanager(_UpperCAmelCase ) snake_case_ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('''bleurt''' ) def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Tuple: """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags class lowerCAmelCase_ ( lowerCamelCase__ ): '''simple docstring''' def UpperCamelCase__ ( self , _UpperCAmelCase ): assert len(input_dict['''input_ids'''] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor: snake_case_ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('''bertscore''' ) def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> int: """simple docstring""" import torch def bert_cos_score_idf(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ): return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_SNAKE_CASE ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('''bert_score.scorer.get_model''' ), patch( '''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf: snake_case_ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('''comet''' ) def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Optional[int]: """simple docstring""" def load_from_checkpoint(SCREAMING_SNAKE_CASE ): class lowerCAmelCase_ : '''simple docstring''' def UpperCamelCase__ ( self , _UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase ): assert len(_UpperCAmelCase ) == 2 snake_case_ = [0.19, 0.92] return scores, sum(_UpperCAmelCase ) / len(_UpperCAmelCase ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('''comet.download_model''' ) as mock_download_model: snake_case_ = None with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint: snake_case_ = load_from_checkpoint yield def __lowerCAmelCase ()-> str: """simple docstring""" snake_case_ = load_metric(os.path.join('''metrics''' , '''seqeval''' ) ) snake_case_ = '''ERROR''' snake_case_ = f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(SCREAMING_SNAKE_CASE , match=re.escape(SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=SCREAMING_SNAKE_CASE )
531
import copy import re class lowerCAmelCase_ : '''simple docstring''' __snake_case = "hp" __snake_case = {} __snake_case = None @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase , _UpperCAmelCase ): snake_case_ = prefix snake_case_ = defaults cls.build_naming_info() @staticmethod def UpperCamelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): if len(_UpperCAmelCase ) == 0: return "" snake_case_ = None if any(char.isdigit() for char in word ): raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_UpperCAmelCase ) + 1 ): snake_case_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: snake_case_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_UpperCAmelCase ): snake_case_ = '''''' while integer != 0: snake_case_ = chr(ord('''A''' ) + integer % 10 ) + s integer //= 10 return s snake_case_ = 0 while True: snake_case_ = word + '''#''' + int_to_alphabetic(_UpperCAmelCase ) if sword in info["reverse_short_word"]: continue else: snake_case_ = sword break snake_case_ = short_word snake_case_ = word return short_word @staticmethod def UpperCamelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): snake_case_ = param_name.split('''_''' ) snake_case_ = [TrialShortNamer.shortname_for_word(_UpperCAmelCase , _UpperCAmelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name snake_case_ = ['''''', '''_'''] for separator in separators: snake_case_ = separator.join(_UpperCAmelCase ) if shortname not in info["reverse_short_param"]: snake_case_ = shortname snake_case_ = param_name return shortname return param_name @staticmethod def UpperCamelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): snake_case_ = TrialShortNamer.shortname_for_key(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = short_name snake_case_ = param_name @classmethod def UpperCamelCase__ ( cls ): if cls.NAMING_INFO is not None: return snake_case_ = { '''short_word''': {}, '''reverse_short_word''': {}, '''short_param''': {}, '''reverse_short_param''': {}, } snake_case_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = info @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase ): cls.build_naming_info() assert cls.PREFIX is not None snake_case_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F'''You should provide a default value for the param name {k} with value {v}''' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue snake_case_ = cls.NAMING_INFO['''short_param'''][k] if isinstance(_UpperCAmelCase , _UpperCAmelCase ): snake_case_ = 1 if v else 0 snake_case_ = '''''' if isinstance(_UpperCAmelCase , (int, float) ) else '''-''' snake_case_ = F'''{key}{sep}{v}''' name.append(_UpperCAmelCase ) return "_".join(_UpperCAmelCase ) @classmethod def UpperCamelCase__ ( cls , _UpperCAmelCase ): snake_case_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": snake_case_ = [] else: snake_case_ = repr.split('''_''' ) snake_case_ = {} for value in values: if "-" in value: snake_case_ , snake_case_ = value.split('''-''' ) else: snake_case_ = re.sub('''[0-9.]''' , '''''' , _UpperCAmelCase ) snake_case_ = float(re.sub('''[^0-9.]''' , '''''' , _UpperCAmelCase ) ) snake_case_ = cls.NAMING_INFO['''reverse_short_param'''][p_k] snake_case_ = p_v for k in cls.DEFAULTS: if k not in parameters: snake_case_ = cls.DEFAULTS[k] return parameters
531
1
def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : Union[str, Any] = len(snake_case_ ) _A : str = [[0] * n for i in range(snake_case_ )] for i in range(snake_case_ ): _A : Optional[Any] = y_points[i] for i in range(2,snake_case_ ): for j in range(snake_case_,snake_case_ ): _A : List[Any] = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
307
# Copyright 2021 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. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def lowerCAmelCase_ ( snake_case_=None ): _A : Union[str, Any] = argparse.ArgumentParser(add_help=snake_case_,allow_abbrev=snake_case_ ) # The main config parser _A : Union[str, Any] = config_command_parser(snake_case_ ) # The subparser to add commands to _A : Union[str, Any] = config_parser.add_subparsers(title="""subcommands""",dest="""subcommand""" ) # Then add other parsers with the parent parser default_command_parser(snake_case_,parents=[parent_parser] ) update_command_parser(snake_case_,parents=[parent_parser] ) return config_parser def lowerCAmelCase_ ( ): _A : Optional[Any] = get_config_parser() _A : List[Any] = config_parser.parse_args() if not hasattr(snake_case_,"""func""" ): config_parser.print_help() exit(1 ) # Run args.func(snake_case_ ) if __name__ == "__main__": main()
307
1
def __UpperCAmelCase ( snake_case_ : list[int] , snake_case_ : list[int] ): '''simple docstring''' if not len(snake_case_ ) == len(snake_case_ ) == 3: raise ValueError("Please enter a valid equation." ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("Both a & b of two equations can't be zero." ) # Extract the coefficients UpperCAmelCase: Any = equationa UpperCAmelCase: Tuple = equationa # Calculate the determinants of the matrices UpperCAmelCase: Optional[int] = aa * ba - aa * ba UpperCAmelCase: Any = ca * ba - ca * ba UpperCAmelCase: Optional[int] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)" ) else: raise ValueError("No solution. (Inconsistent system)" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: UpperCAmelCase: Any = determinant_x / determinant UpperCAmelCase: Union[str, Any] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
718
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCamelCase ( lowercase ): lowerCamelCase__: Any = '''new-model''' if is_tf_available(): class __lowerCamelCase ( lowercase ): lowerCamelCase__: int = NewModelConfig @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def A__ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase: int = "bert-base-cased" UpperCAmelCase: Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: int = TFAutoModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase: Optional[int] = "bert-base-cased" UpperCAmelCase: Any = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: Tuple = TFAutoModelForPreTraining.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase: str = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case ) UpperCAmelCase , UpperCAmelCase: Optional[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> str: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase: List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> str: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase: List[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: Union[str, Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case ) UpperCAmelCase , UpperCAmelCase: Any = TFAutoModelForMaskedLM.from_pretrained(__snake_case , output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> str: """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase: str = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: int = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case ) UpperCAmelCase , UpperCAmelCase: str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> Dict: """simple docstring""" for model_name in ["bert-base-uncased"]: UpperCAmelCase: str = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: Dict = TFAutoModelForSequenceClassification.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def A__ ( self ) -> Optional[Any]: """simple docstring""" for model_name in ["bert-base-uncased"]: UpperCAmelCase: Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: List[Any] = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow @require_tensorflow_probability def A__ ( self ) -> Any: """simple docstring""" for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: UpperCAmelCase: Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: Any = TFAutoModelForTableQuestionAnswering.from_pretrained(__snake_case ) UpperCAmelCase , UpperCAmelCase: Optional[Any] = TFAutoModelForTableQuestionAnswering.from_pretrained( __snake_case , output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase: Optional[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_4_4_1_0 ) def A__ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase: Any = TFAutoModelWithLMHead.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_4_4_1_0 ) def A__ ( self ) -> Dict: """simple docstring""" UpperCAmelCase: int = TFAutoModel.from_pretrained("sgugger/funnel-random-tiny" ) self.assertIsInstance(__snake_case , __snake_case ) UpperCAmelCase: int = copy.deepcopy(model.config ) UpperCAmelCase: int = ["FunnelBaseModel"] UpperCAmelCase: Optional[Any] = TFAutoModel.from_config(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__snake_case ) UpperCAmelCase: Dict = TFAutoModel.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def A__ ( self ) -> Optional[int]: """simple docstring""" try: AutoConfig.register("new-model" , __snake_case ) UpperCAmelCase: Tuple = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(__snake_case ): auto_class.register(__snake_case , __snake_case ) auto_class.register(__snake_case , __snake_case ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__snake_case ): auto_class.register(__snake_case , __snake_case ) # Now that the config is registered, it can be used as any other config with the auto-API UpperCAmelCase: Dict = BertModelTester(self ).get_config() UpperCAmelCase: str = NewModelConfig(**tiny_config.to_dict() ) UpperCAmelCase: Tuple = auto_class.from_config(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__snake_case ) UpperCAmelCase: Dict = auto_class.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def A__ ( self ) -> Tuple: """simple docstring""" with self.assertRaisesRegex( __snake_case , "bert-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase: Union[str, Any] = TFAutoModel.from_pretrained("bert-base" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" with self.assertRaisesRegex( __snake_case , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase: int = TFAutoModel.from_pretrained(__snake_case , revision="aaaaaa" ) def A__ ( self ) -> Optional[int]: """simple docstring""" with self.assertRaisesRegex( __snake_case , "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin" , ): UpperCAmelCase: Union[str, Any] = TFAutoModel.from_pretrained("hf-internal-testing/config-no-model" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" with self.assertRaisesRegex(__snake_case , "Use `from_pt=True` to load this model" ): UpperCAmelCase: Any = TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" ) def A__ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase: str = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) with RequestCounter() as counter: UpperCAmelCase: List[Any] = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint UpperCAmelCase: str = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) with RequestCounter() as counter: UpperCAmelCase: int = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
166
0
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class lowerCamelCase_ ( unittest.TestCase ): def __lowercase ( self : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" SCREAMING_SNAKE_CASE : int = jnp.ones((batch_size, length) ) / length return scores def __lowercase ( self : Any ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Tuple = 20 SCREAMING_SNAKE_CASE : Optional[int] = self._get_uniform_logits(batch_size=2 , length=lowerCAmelCase__ ) # tweak scores to not be uniform anymore SCREAMING_SNAKE_CASE : Dict = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch SCREAMING_SNAKE_CASE : Optional[int] = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax SCREAMING_SNAKE_CASE : Any = jax.nn.softmax(lowerCAmelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE : Tuple = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxTemperatureLogitsWarper(temperature=1.3 ) SCREAMING_SNAKE_CASE : Optional[int] = jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase__ , scores.copy() , cur_len=lowerCAmelCase__ ) , axis=-1 ) SCREAMING_SNAKE_CASE : str = jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase__ , scores.copy() , cur_len=lowerCAmelCase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def __lowercase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : int = 10 SCREAMING_SNAKE_CASE : List[str] = 2 # create ramp distribution SCREAMING_SNAKE_CASE : List[str] = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() SCREAMING_SNAKE_CASE : Union[str, Any] = ramp_logits[1:, : vocab_size // 2] + vocab_size SCREAMING_SNAKE_CASE : Optional[int] = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE : Tuple = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case SCREAMING_SNAKE_CASE : Union[str, Any] = 5 SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) SCREAMING_SNAKE_CASE : List[str] = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, length) ).copy() SCREAMING_SNAKE_CASE : str = top_k_warp_safety_check(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Dict = 10 SCREAMING_SNAKE_CASE : List[str] = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) SCREAMING_SNAKE_CASE : Optional[Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxTopPLogitsWarper(0.8 ) SCREAMING_SNAKE_CASE : Tuple = np.exp(top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 SCREAMING_SNAKE_CASE : Dict = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits SCREAMING_SNAKE_CASE : int = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme SCREAMING_SNAKE_CASE : List[str] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept SCREAMING_SNAKE_CASE : Optional[Any] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) SCREAMING_SNAKE_CASE : Tuple = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def __lowercase ( self : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = 20 SCREAMING_SNAKE_CASE : Dict = 4 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : int = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) # check that min length is applied at length 5 SCREAMING_SNAKE_CASE : List[str] = ids_tensor((batch_size, 20) , vocab_size=20 ) SCREAMING_SNAKE_CASE : int = 5 SCREAMING_SNAKE_CASE : Union[str, Any] = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = min_dist_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 SCREAMING_SNAKE_CASE : List[Any] = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = 15 SCREAMING_SNAKE_CASE : List[str] = min_dist_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = 20 SCREAMING_SNAKE_CASE : Union[str, Any] = 4 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) # check that all scores are -inf except the bos_token_id score SCREAMING_SNAKE_CASE : List[str] = ids_tensor((batch_size, 1) , vocab_size=20 ) SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Any = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 SCREAMING_SNAKE_CASE : str = 3 SCREAMING_SNAKE_CASE : Tuple = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def __lowercase ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = 20 SCREAMING_SNAKE_CASE : Optional[Any] = 4 SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : List[str] = 5 SCREAMING_SNAKE_CASE : Optional[Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor((batch_size, 4) , vocab_size=20 ) SCREAMING_SNAKE_CASE : Optional[int] = 4 SCREAMING_SNAKE_CASE : List[Any] = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached SCREAMING_SNAKE_CASE : List[str] = 3 SCREAMING_SNAKE_CASE : Tuple = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Dict = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 4 SCREAMING_SNAKE_CASE : Dict = 10 SCREAMING_SNAKE_CASE : List[str] = 15 SCREAMING_SNAKE_CASE : List[Any] = 2 SCREAMING_SNAKE_CASE : Optional[Any] = 1 SCREAMING_SNAKE_CASE : Optional[Any] = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor((batch_size, sequence_length) , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = input_ids.copy() SCREAMING_SNAKE_CASE : Tuple = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE : Any = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE : Tuple = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE : Optional[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = 10 # no processor list SCREAMING_SNAKE_CASE : Union[str, Any] = temp_dist_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Dict = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = min_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = bos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = eos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # with processor list SCREAMING_SNAKE_CASE : str = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE : Union[str, Any] = processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def __lowercase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : int = 10 SCREAMING_SNAKE_CASE : Optional[Any] = 15 SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : str = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor((batch_size, sequence_length) , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = input_ids.copy() SCREAMING_SNAKE_CASE : int = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE : int = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE : List[Any] = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE : Any = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Any = 10 # no processor list def run_no_processor_list(lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[int] = temp_dist_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = min_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = bos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = eos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) return scores # with processor list def run_processor_list(lowerCAmelCase__ : str , lowerCAmelCase__ : Dict , lowerCAmelCase__ : int ): SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE : Union[str, Any] = processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) return scores SCREAMING_SNAKE_CASE : Optional[int] = jax.jit(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = jax.jit(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Dict = jitted_run_no_processor_list(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = jitted_run_processor_list(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
527
from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __UpperCamelCase : str = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE( a_ ): _UpperCAmelCase = ["input_values", "padding_mask"] def __init__( self: List[Any] , UpperCamelCase: int = 1 , UpperCamelCase: int = 2_40_00 , UpperCamelCase: float = 0.0 , UpperCamelCase: float = None , UpperCamelCase: float = None , **UpperCamelCase: Optional[int] , ) -> int: super().__init__(feature_size=UpperCamelCase , sampling_rate=UpperCamelCase , padding_value=UpperCamelCase , **UpperCamelCase ) snake_case__ = chunk_length_s snake_case__ = overlap @property def lowerCAmelCase_ ( self: Optional[int] ) -> Optional[int]: if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def lowerCAmelCase_ ( self: Union[str, Any] ) -> Optional[int]: if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self: Union[str, Any] , UpperCamelCase: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase: Optional[Union[bool, str, PaddingStrategy]] = None , UpperCamelCase: Optional[bool] = False , UpperCamelCase: Optional[int] = None , UpperCamelCase: Optional[Union[str, TensorType]] = None , UpperCamelCase: Optional[int] = None , ) -> BatchFeature: 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 audio 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.' ) if padding and truncation: raise ValueError('Both padding and truncation were set. Make sure you only set one.' ) elif padding is None: # by default let's pad the inputs snake_case__ = True snake_case__ = bool( isinstance(UpperCamelCase , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) ) if is_batched: snake_case__ = [np.asarray(UpperCamelCase , dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(UpperCamelCase , np.ndarray ): snake_case__ = np.asarray(UpperCamelCase , dtype=np.floataa ) elif isinstance(UpperCamelCase , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): snake_case__ = raw_audio.astype(np.floataa ) # always return batch if not is_batched: snake_case__ = [np.asarray(UpperCamelCase ).T] # verify inputs are valid for idx, example in enumerate(UpperCamelCase ): if example.ndim > 2: raise ValueError(F'''Expected input shape (channels, length) but got shape {example.shape}''' ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(F'''Expected mono audio but example has {example.shape[-1]} channels''' ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(F'''Expected stereo audio but example has {example.shape[-1]} channels''' ) snake_case__ = None snake_case__ = BatchFeature({'input_values': raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: snake_case__ = min(array.shape[0] for array in raw_audio ) snake_case__ = int(np.floor(max_length / self.chunk_stride ) ) snake_case__ = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: snake_case__ = max(array.shape[0] for array in raw_audio ) snake_case__ = int(np.ceil(max_length / self.chunk_stride ) ) snake_case__ = (nb_step - 1) * self.chunk_stride + self.chunk_length snake_case__ = 'max_length' else: snake_case__ = input_values # normal padding on batch if padded_inputs is None: snake_case__ = self.pad( UpperCamelCase , max_length=UpperCamelCase , truncation=UpperCamelCase , padding=UpperCamelCase , return_attention_mask=UpperCamelCase , ) if padding: snake_case__ = padded_inputs.pop('attention_mask' ) snake_case__ = [] for example in padded_inputs.pop('input_values' ): if self.feature_size == 1: snake_case__ = example[..., None] input_values.append(example.T ) snake_case__ = input_values if return_tensors is not None: snake_case__ = padded_inputs.convert_to_tensors(UpperCamelCase ) return padded_inputs
328
0
class _lowercase : '''simple docstring''' def __init__( self :str ) -> Dict: __SCREAMING_SNAKE_CASE : List[Any] = {} def __magic_name__( self :int ) -> None: print(self.vertex ) for i in self.vertex: print(lowerCAmelCase__ , ''' -> ''' , ''' -> '''.join([str(lowerCAmelCase__ ) for j in self.vertex[i]] ) ) def __magic_name__( self :str , lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> None: # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(lowerCAmelCase__ ) else: # else make a new vertex __SCREAMING_SNAKE_CASE : int = [to_vertex] def __magic_name__( self :Any ) -> None: # visited array for storing already visited nodes __SCREAMING_SNAKE_CASE : str = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) def __magic_name__( self :str , lowerCAmelCase__ :int , lowerCAmelCase__ :list ) -> None: # mark start vertex as visited __SCREAMING_SNAKE_CASE : Optional[int] = True print(lowerCAmelCase__ , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __lowerCAmelCase : Tuple =Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
260
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _UpperCamelCase ( lowercase__ , lowercase__=0.999 , lowercase__="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(lowercase__ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowercase__ ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [] for i in range(lowercase__ ): __SCREAMING_SNAKE_CASE : Tuple = i / num_diffusion_timesteps __SCREAMING_SNAKE_CASE : Optional[Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowercase__ ) / alpha_bar_fn(lowercase__ ) , lowercase__ ) ) return torch.tensor(lowercase__ , dtype=torch.floataa ) class _lowercase ( A__ , A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = [e.name for e in KarrasDiffusionSchedulers] SCREAMING_SNAKE_CASE__ : str = 2 @register_to_config def __init__( self :Tuple , lowerCAmelCase__ :int = 1_000 , lowerCAmelCase__ :float = 0.0_0085 , lowerCAmelCase__ :float = 0.012 , lowerCAmelCase__ :str = "linear" , lowerCAmelCase__ :Optional[Union[np.ndarray, List[float]]] = None , lowerCAmelCase__ :str = "epsilon" , lowerCAmelCase__ :str = "linspace" , lowerCAmelCase__ :int = 0 , ) -> List[Any]: if trained_betas is not None: __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) elif beta_schedule == "linear": __SCREAMING_SNAKE_CASE : Tuple = torch.linspace(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __SCREAMING_SNAKE_CASE : Dict = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCAmelCase__ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __SCREAMING_SNAKE_CASE : Optional[Any] = betas_for_alpha_bar(lowerCAmelCase__ ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __SCREAMING_SNAKE_CASE : Dict = 1.0 - self.betas __SCREAMING_SNAKE_CASE : Tuple = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def __magic_name__( self :Any , lowerCAmelCase__ :int , lowerCAmelCase__ :Any=None ) -> Tuple: if schedule_timesteps is None: __SCREAMING_SNAKE_CASE : Any = self.timesteps __SCREAMING_SNAKE_CASE : Tuple = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 if len(lowerCAmelCase__ ) > 1 else 0 else: __SCREAMING_SNAKE_CASE : str = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase__ ) else timestep __SCREAMING_SNAKE_CASE : Optional[int] = self._index_counter[timestep_int] return indices[pos].item() @property def __magic_name__( self :Optional[Any] ) -> List[str]: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __magic_name__( self :Any , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :Union[float, torch.FloatTensor] , ) -> torch.FloatTensor: __SCREAMING_SNAKE_CASE : str = self.index_for_timestep(lowerCAmelCase__ ) if self.state_in_first_order: __SCREAMING_SNAKE_CASE : Any = self.sigmas[step_index] else: __SCREAMING_SNAKE_CASE : Tuple = self.sigmas_interpol[step_index] __SCREAMING_SNAKE_CASE : List[Any] = sample / ((sigma**2 + 1) ** 0.5) return sample def __magic_name__( self :Dict , lowerCAmelCase__ :int , lowerCAmelCase__ :Union[str, torch.device] = None , lowerCAmelCase__ :Optional[int] = None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE : Dict = num_inference_steps __SCREAMING_SNAKE_CASE : Optional[int] = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __SCREAMING_SNAKE_CASE : str = np.linspace(0 , num_train_timesteps - 1 , lowerCAmelCase__ , dtype=lowerCAmelCase__ )[::-1].copy() elif self.config.timestep_spacing == "leading": __SCREAMING_SNAKE_CASE : Any = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __SCREAMING_SNAKE_CASE : Any = (np.arange(0 , lowerCAmelCase__ ) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase__ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __SCREAMING_SNAKE_CASE : Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __SCREAMING_SNAKE_CASE : Optional[Any] = (np.arange(lowerCAmelCase__ , 0 , -step_ratio )).round().copy().astype(lowerCAmelCase__ ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __SCREAMING_SNAKE_CASE : Optional[int] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.from_numpy(np.log(lowerCAmelCase__ ) ).to(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[Any] = np.interp(lowerCAmelCase__ , np.arange(0 , len(lowerCAmelCase__ ) ) , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ) # interpolate sigmas __SCREAMING_SNAKE_CASE : int = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __SCREAMING_SNAKE_CASE : Dict = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __SCREAMING_SNAKE_CASE : Any = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(lowerCAmelCase__ ).startswith('''mps''' ): # mps does not support float64 __SCREAMING_SNAKE_CASE : Dict = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ , dtype=torch.floataa ) else: __SCREAMING_SNAKE_CASE : str = torch.from_numpy(lowerCAmelCase__ ).to(lowerCAmelCase__ ) # interpolate timesteps __SCREAMING_SNAKE_CASE : Union[str, Any] = self.sigma_to_t(lowerCAmelCase__ ).to(lowerCAmelCase__ , dtype=timesteps.dtype ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __SCREAMING_SNAKE_CASE : int = torch.cat([timesteps[:1], interleaved_timesteps] ) __SCREAMING_SNAKE_CASE : Dict = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __SCREAMING_SNAKE_CASE : List[str] = defaultdict(lowerCAmelCase__ ) def __magic_name__( self :int , lowerCAmelCase__ :List[Any] ) -> Union[str, Any]: # get log sigma __SCREAMING_SNAKE_CASE : int = sigma.log() # get distribution __SCREAMING_SNAKE_CASE : str = log_sigma - self.log_sigmas[:, None] # get sigmas range __SCREAMING_SNAKE_CASE : Any = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __SCREAMING_SNAKE_CASE : Any = low_idx + 1 __SCREAMING_SNAKE_CASE : Tuple = self.log_sigmas[low_idx] __SCREAMING_SNAKE_CASE : Dict = self.log_sigmas[high_idx] # interpolate sigmas __SCREAMING_SNAKE_CASE : List[Any] = (low - log_sigma) / (low - high) __SCREAMING_SNAKE_CASE : Dict = w.clamp(0 , 1 ) # transform interpolation to time range __SCREAMING_SNAKE_CASE : Tuple = (1 - w) * low_idx + w * high_idx __SCREAMING_SNAKE_CASE : List[Any] = t.view(sigma.shape ) return t @property def __magic_name__( self :Union[str, Any] ) -> Optional[int]: return self.sample is None def __magic_name__( self :List[Any] , lowerCAmelCase__ :Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase__ :Union[float, torch.FloatTensor] , lowerCAmelCase__ :Union[torch.FloatTensor, np.ndarray] , lowerCAmelCase__ :bool = True , ) -> Union[SchedulerOutput, Tuple]: __SCREAMING_SNAKE_CASE : Dict = self.index_for_timestep(lowerCAmelCase__ ) # advance index counter by 1 __SCREAMING_SNAKE_CASE : Tuple = timestep.cpu().item() if torch.is_tensor(lowerCAmelCase__ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __SCREAMING_SNAKE_CASE : Dict = self.sigmas[step_index] __SCREAMING_SNAKE_CASE : Dict = self.sigmas_interpol[step_index + 1] __SCREAMING_SNAKE_CASE : List[str] = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __SCREAMING_SNAKE_CASE : List[str] = self.sigmas[step_index - 1] __SCREAMING_SNAKE_CASE : Any = self.sigmas_interpol[step_index] __SCREAMING_SNAKE_CASE : Optional[int] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : List[str] = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __SCREAMING_SNAKE_CASE : str = sigma_hat if self.state_in_first_order else sigma_interpol __SCREAMING_SNAKE_CASE : Optional[Any] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __SCREAMING_SNAKE_CASE : Any = sigma_hat if self.state_in_first_order else sigma_interpol __SCREAMING_SNAKE_CASE : List[str] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __SCREAMING_SNAKE_CASE : int = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __SCREAMING_SNAKE_CASE : List[str] = sigma_interpol - sigma_hat # store for 2nd order step __SCREAMING_SNAKE_CASE : List[str] = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __SCREAMING_SNAKE_CASE : List[str] = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __SCREAMING_SNAKE_CASE : Any = sigma_next - sigma_hat __SCREAMING_SNAKE_CASE : Optional[int] = self.sample __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Tuple = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowerCAmelCase__ ) def __magic_name__( self :List[Any] , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :torch.FloatTensor , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples __SCREAMING_SNAKE_CASE : Tuple = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase__ ): # mps does not support float64 __SCREAMING_SNAKE_CASE : Tuple = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.timesteps.to(original_samples.device ) __SCREAMING_SNAKE_CASE : List[str] = timesteps.to(original_samples.device ) __SCREAMING_SNAKE_CASE : Dict = [self.index_for_timestep(lowerCAmelCase__ , lowerCAmelCase__ ) for t in timesteps] __SCREAMING_SNAKE_CASE : Optional[Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __SCREAMING_SNAKE_CASE : List[Any] = sigma.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = original_samples + noise * sigma return noisy_samples def __len__( self :Tuple ) -> Optional[Any]: return self.config.num_train_timesteps
260
1
from __future__ import annotations class _snake_case : def __init__( self , a) -> None: SCREAMING_SNAKE_CASE = data SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def lowerCamelCase__ (_UpperCAmelCase): # In Order traversal of the tree if tree: display(tree.left) print(tree.data) display(tree.right) def lowerCamelCase__ (_UpperCAmelCase): return 1 + max(depth_of_tree(tree.left) , depth_of_tree(tree.right)) if tree else 0 def lowerCamelCase__ (_UpperCAmelCase): if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right) else: return not tree.left and not tree.right def lowerCamelCase__ (): # Main function for testing. SCREAMING_SNAKE_CASE = Node(1) SCREAMING_SNAKE_CASE = Node(2) SCREAMING_SNAKE_CASE = Node(3) SCREAMING_SNAKE_CASE = Node(4) SCREAMING_SNAKE_CASE = Node(5) SCREAMING_SNAKE_CASE = Node(6) SCREAMING_SNAKE_CASE = Node(7) SCREAMING_SNAKE_CASE = Node(8) SCREAMING_SNAKE_CASE = Node(9) print(is_full_binary_tree(_UpperCAmelCase)) print(depth_of_tree(_UpperCAmelCase)) print('Tree is: ') display(_UpperCAmelCase) if __name__ == "__main__": main()
73
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase : Union[str, Any] = logging.get_logger(__name__) _lowercase : List[Any] = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class _UpperCAmelCase ( _lowerCAmelCase ): a__ : Tuple = "camembert" def __init__( self : Union[str, Any] , _lowercase : Any=3_05_22 , _lowercase : Any=7_68 , _lowercase : Union[str, Any]=12 , _lowercase : List[str]=12 , _lowercase : int=30_72 , _lowercase : Union[str, Any]="gelu" , _lowercase : Dict=0.1 , _lowercase : Optional[int]=0.1 , _lowercase : int=5_12 , _lowercase : Optional[Any]=2 , _lowercase : Dict=0.02 , _lowercase : Optional[Any]=1E-12 , _lowercase : Optional[int]=1 , _lowercase : Optional[Any]=0 , _lowercase : Tuple=2 , _lowercase : List[Any]="absolute" , _lowercase : List[Any]=True , _lowercase : Dict=None , **_lowercase : Optional[int] , ): super().__init__(pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , **_lowercase ) __UpperCAmelCase = vocab_size __UpperCAmelCase = hidden_size __UpperCAmelCase = num_hidden_layers __UpperCAmelCase = num_attention_heads __UpperCAmelCase = hidden_act __UpperCAmelCase = intermediate_size __UpperCAmelCase = hidden_dropout_prob __UpperCAmelCase = attention_probs_dropout_prob __UpperCAmelCase = max_position_embeddings __UpperCAmelCase = type_vocab_size __UpperCAmelCase = initializer_range __UpperCAmelCase = layer_norm_eps __UpperCAmelCase = position_embedding_type __UpperCAmelCase = use_cache __UpperCAmelCase = classifier_dropout class _UpperCAmelCase ( _lowerCAmelCase ): @property def a ( self : Tuple ): if self.task == "multiple-choice": __UpperCAmelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __UpperCAmelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
49
0
'''simple docstring''' 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 _lowerCAmelCase ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 42 class _lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__(self , lowercase = 65536 , lowercase = None , lowercase = 2 , lowercase = 2 , lowercase = 0 , lowercase = "fourier" , lowercase = True , lowercase = False , lowercase = 0.0 , lowercase = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , lowercase = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , lowercase = "UNetMidBlock1D" , lowercase = None , lowercase = (32, 32, 64) , lowercase = None , lowercase = 8 , lowercase = 1 , lowercase = False , ): super().__init__() A_ : Optional[int] = sample_size # time if time_embedding_type == "fourier": A_ : Union[str, Any] = GaussianFourierProjection( embedding_size=8 , set_W_to_weight=_a , log=_a , flip_sin_to_cos=_a ) A_ : Any = 2 * block_out_channels[0] elif time_embedding_type == "positional": A_ : str = Timesteps( block_out_channels[0] , flip_sin_to_cos=_a , downscale_freq_shift=_a ) A_ : int = block_out_channels[0] if use_timestep_embedding: A_ : List[str] = block_out_channels[0] * 4 A_ : str = TimestepEmbedding( in_channels=_a , time_embed_dim=_a , act_fn=_a , out_dim=block_out_channels[0] , ) A_ : Dict = nn.ModuleList([] ) A_ : Optional[int] = None A_ : List[Any] = nn.ModuleList([] ) A_ : Optional[int] = None # down A_ : Union[str, Any] = in_channels for i, down_block_type in enumerate(_a ): A_ : List[str] = output_channel A_ : str = block_out_channels[i] if i == 0: input_channel += extra_in_channels A_ : Any = i == len(_a ) - 1 A_ : List[str] = get_down_block( _a , num_layers=_a , in_channels=_a , out_channels=_a , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , ) self.down_blocks.append(_a ) # mid A_ : Union[str, Any] = get_mid_block( _a , 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=_a , add_downsample=_a , ) # up A_ : List[Any] = list(reversed(_a ) ) A_ : str = reversed_block_out_channels[0] if out_block_type is None: A_ : List[str] = out_channels else: A_ : Tuple = block_out_channels[0] for i, up_block_type in enumerate(_a ): A_ : str = output_channel A_ : Union[str, Any] = ( reversed_block_out_channels[i + 1] if i < len(_a ) - 1 else final_upsample_channels ) A_ : Any = i == len(_a ) - 1 A_ : Any = get_up_block( _a , num_layers=_a , in_channels=_a , out_channels=_a , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , ) self.up_blocks.append(_a ) A_ : Tuple = output_channel # out A_ : Optional[int] = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 ) A_ : Optional[Any] = get_out_block( out_block_type=_a , num_groups_out=_a , embed_dim=block_out_channels[0] , out_channels=_a , act_fn=_a , fc_dim=block_out_channels[-1] // 4 , ) def _a (self , lowercase , lowercase , lowercase = True , ): A_ : str = timestep if not torch.is_tensor(_a ): A_ : str = torch.tensor([timesteps] , dtype=torch.long , device=sample.device ) elif torch.is_tensor(_a ) and len(timesteps.shape ) == 0: A_ : int = timesteps[None].to(sample.device ) A_ : Union[str, Any] = self.time_proj(_a ) if self.config.use_timestep_embedding: A_ : List[str] = self.time_mlp(_a ) else: A_ : Optional[Any] = timestep_embed[..., None] A_ : Any = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) A_ : str = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down A_ : int = () for downsample_block in self.down_blocks: A_ : Optional[Any] = downsample_block(hidden_states=_a , temb=_a ) down_block_res_samples += res_samples # 3. mid if self.mid_block: A_ : Dict = self.mid_block(_a , _a ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): A_ : str = down_block_res_samples[-1:] A_ : Union[str, Any] = down_block_res_samples[:-1] A_ : Optional[Any] = upsample_block(_a , res_hidden_states_tuple=_a , temb=_a ) # 5. post-process if self.out_block: A_ : Any = self.out_block(_a , _a ) if not return_dict: return (sample,) return UNetaDOutput(sample=_a )
710
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowerCamelCase :Union[str, Any] = logging.get_logger(__name__) class _lowerCAmelCase ( __UpperCAmelCase ): __SCREAMING_SNAKE_CASE : Tuple = 'linear' __SCREAMING_SNAKE_CASE : Union[str, Any] = 'cosine' __SCREAMING_SNAKE_CASE : Union[str, Any] = 'cosine_with_restarts' __SCREAMING_SNAKE_CASE : Union[str, Any] = 'polynomial' __SCREAMING_SNAKE_CASE : Optional[int] = 'constant' __SCREAMING_SNAKE_CASE : str = 'constant_with_warmup' __SCREAMING_SNAKE_CASE : Dict = 'piecewise_constant' def a ( lowerCamelCase__ , lowerCamelCase__ = -1 ): '''simple docstring''' return LambdaLR(lowerCamelCase__ , lambda lowerCamelCase__ : 1 , last_epoch=lowerCamelCase__ ) def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = -1 ): '''simple docstring''' def lr_lambda(lowerCamelCase__ ): if current_step < num_warmup_steps: return float(lowerCamelCase__ ) / float(max(1.0 , lowerCamelCase__ ) ) return 1.0 return LambdaLR(lowerCamelCase__ , lowerCamelCase__ , last_epoch=lowerCamelCase__ ) def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = -1 ): '''simple docstring''' A_ : Optional[Any] = {} A_ : Optional[Any] = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: A_, A_ : Union[str, Any] = rule_str.split(""":""" ) A_ : Union[str, Any] = int(lowerCamelCase__ ) A_ : List[Any] = float(lowerCamelCase__ ) A_ : Union[str, Any] = value A_ : Optional[int] = float(rule_list[-1] ) def create_rules_function(lowerCamelCase__ , lowerCamelCase__ ): def rule_func(lowerCamelCase__ ) -> float: A_ : str = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(lowerCamelCase__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func A_ : str = create_rules_function(lowerCamelCase__ , lowerCamelCase__ ) return LambdaLR(lowerCamelCase__ , lowerCamelCase__ , last_epoch=lowerCamelCase__ ) def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=-1 ): '''simple docstring''' def lr_lambda(lowerCamelCase__ ): if current_step < num_warmup_steps: return float(lowerCamelCase__ ) / float(max(1 , lowerCamelCase__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = 0.5 , lowerCamelCase__ = -1 ): '''simple docstring''' def lr_lambda(lowerCamelCase__ ): if current_step < num_warmup_steps: return float(lowerCamelCase__ ) / float(max(1 , lowerCamelCase__ ) ) A_ : Optional[Any] = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(lowerCamelCase__ ) * 2.0 * progress )) ) return LambdaLR(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = 1 , lowerCamelCase__ = -1 ): '''simple docstring''' def lr_lambda(lowerCamelCase__ ): if current_step < num_warmup_steps: return float(lowerCamelCase__ ) / float(max(1 , lowerCamelCase__ ) ) A_ : int = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(lowerCamelCase__ ) * progress) % 1.0) )) ) return LambdaLR(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=1E-7 , lowerCamelCase__=1.0 , lowerCamelCase__=-1 ): '''simple docstring''' A_ : Optional[Any] = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(f'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(lowerCamelCase__ ): if current_step < num_warmup_steps: return float(lowerCamelCase__ ) / float(max(1 , lowerCamelCase__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: A_ : str = lr_init - lr_end A_ : Tuple = num_training_steps - num_warmup_steps A_ : Optional[int] = 1 - (current_step - num_warmup_steps) / decay_steps A_ : Optional[int] = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase :List[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = 1 , lowerCamelCase__ = 1.0 , lowerCamelCase__ = -1 , ): '''simple docstring''' A_ : Optional[Any] = SchedulerType(lowerCamelCase__ ) A_ : Tuple = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(lowerCamelCase__ , last_epoch=lowerCamelCase__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(lowerCamelCase__ , step_rules=lowerCamelCase__ , last_epoch=lowerCamelCase__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(lowerCamelCase__ , num_warmup_steps=lowerCamelCase__ , last_epoch=lowerCamelCase__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( lowerCamelCase__ , num_warmup_steps=lowerCamelCase__ , num_training_steps=lowerCamelCase__ , num_cycles=lowerCamelCase__ , last_epoch=lowerCamelCase__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( lowerCamelCase__ , num_warmup_steps=lowerCamelCase__ , num_training_steps=lowerCamelCase__ , power=lowerCamelCase__ , last_epoch=lowerCamelCase__ , ) return schedule_func( lowerCamelCase__ , num_warmup_steps=lowerCamelCase__ , num_training_steps=lowerCamelCase__ , last_epoch=lowerCamelCase__ )
686
0
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='session' ) def __lowerCAmelCase( ) -> Optional[Any]: """simple docstring""" _A = 10 _A = datasets.Features( { 'tokens': datasets.Sequence(datasets.Value('string' ) ), 'labels': datasets.Sequence(datasets.ClassLabel(names=['negative', 'positive'] ) ), 'answers': datasets.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), 'id': datasets.Value('int64' ), } ) _A = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(_SCREAMING_SNAKE_CASE ) ), } , features=_SCREAMING_SNAKE_CASE , ) return dataset @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=_SCREAMING_SNAKE_CASE ) return filename # FILE_CONTENT + files __A : Union[str, Any] = "\\n Text data.\n Second line of data." @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'file.txt' _A = FILE_CONTENT with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return filename @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" import bza _A = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' _A = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) with bza.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" import gzip _A = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) _A = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) with gzip.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if datasets.config.LZ4_AVAILABLE: import lza.frame _A = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' _A = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) with lza.frame.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" if datasets.config.PY7ZR_AVAILABLE: import pyazr _A = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as archive: archive.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" import tarfile _A = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" import lzma _A = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' _A = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) with lzma.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" import zipfile _A = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd _A = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' _A = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) with zstd.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'file.xml' _A = textwrap.dedent( '\\n <?xml version="1.0" encoding="UTF-8" ?>\n <tmx version="1.4">\n <header segtype="sentence" srclang="ca" />\n <body>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang="en"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang="en"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang="en"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang="en"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang="en"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return filename __A : Optional[int] = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] __A : Optional[Any] = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] __A : Any = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } __A : Optional[Any] = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] __A : str = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope='session' ) def __lowerCAmelCase( ) -> List[str]: """simple docstring""" return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _A = datasets.Dataset.from_dict(_SCREAMING_SNAKE_CASE ) _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(_SCREAMING_SNAKE_CASE ) ) as con: _A = con.cursor() cur.execute('CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)' ) for item in DATA: cur.execute('INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(_SCREAMING_SNAKE_CASE , 'w' , newline='' ) as f: _A = csv.DictWriter(_SCREAMING_SNAKE_CASE , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(_SCREAMING_SNAKE_CASE , 'w' , newline='' ) as f: _A = csv.DictWriter(_SCREAMING_SNAKE_CASE , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" import bza _A = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(_SCREAMING_SNAKE_CASE , 'rb' ) as f: _A = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV' ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) _A = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: _A = pq.ParquetWriter(_SCREAMING_SNAKE_CASE , schema=_SCREAMING_SNAKE_CASE ) _A = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(_SCREAMING_SNAKE_CASE ) )] for k in DATA[0]} , schema=_SCREAMING_SNAKE_CASE ) writer.write_table(_SCREAMING_SNAKE_CASE ) writer.close() return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _A = {'data': DATA} with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) _A = {'data': DATA_DICT_OF_LISTS} with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA_312: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _A = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in DATA_STR: f.write(json.dumps(_SCREAMING_SNAKE_CASE ) + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" import gzip _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(_SCREAMING_SNAKE_CASE , 'rb' ) as orig_file: with gzip.open(_SCREAMING_SNAKE_CASE , 'wb' ) as zipped_file: zipped_file.writelines(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" import gzip _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(_SCREAMING_SNAKE_CASE , 'rb' ) as orig_file: with gzip.open(_SCREAMING_SNAKE_CASE , 'wb' ) as zipped_file: zipped_file.writelines(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('nested' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.add(_SCREAMING_SNAKE_CASE , arcname=os.path.join('nested' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = ['0', '1', '2', '3'] _A = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _A = ['0', '1', '2', '3'] _A = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _A = ['0', '1', '2', '3'] _A = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(_SCREAMING_SNAKE_CASE , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.join('main_dir' , os.path.basename(_SCREAMING_SNAKE_CASE ) ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename('unsupported.ext' ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _A = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) _A = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( ) -> Dict: """simple docstring""" return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def __lowerCAmelCase( ) -> Union[str, Any]: """simple docstring""" return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _A = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(_SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ) ) f.write(_SCREAMING_SNAKE_CASE , arcname=os.path.basename(_SCREAMING_SNAKE_CASE ).replace('.jpg' , '2.jpg' ) ) return path @pytest.fixture(scope='session' ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _A = tmp_path_factory.mktemp('data_dir' ) (data_dir / "subdir").mkdir() with open(data_dir / 'subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / 'subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden file with open(data_dir / 'subdir' / '.test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '.subdir' / 'train.txt' , 'w' ) as f: f.write('foo\n' * 10 ) with open(data_dir / '.subdir' / 'test.txt' , 'w' ) as f: f.write('bar\n' * 10 ) return data_dir
27
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _a : List[str] = { '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: _a : Optional[Any] = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] _a : str = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] _a : Tuple = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): _a : Dict = [ '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 _a : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
479
0
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowerCamelCase_ : Dict = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('''''', '''|''', '''|'''), datarow=DataRow('''''', '''|''', '''|'''), padding=1, with_header_hide=None, ) lowerCamelCase_ : Tuple = [] lowerCamelCase_ : Optional[int] = [] lowerCamelCase_ : List[str] = {'''type''': '''section''', '''text''': {'''type''': '''plain_text''', '''text''': '''No failed tests! 🤗''', '''emoji''': True}} lowerCamelCase_ : Optional[Any] = [ { '''type''': '''header''', '''text''': { '''type''': '''plain_text''', '''text''': f"""🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results""", '''emoji''': True, }, } ] lowerCamelCase_ : Tuple = 0 for log in Path().glob('''*.log'''): lowerCamelCase_ : str = 0 with open(log, '''r''') as f: for line in f: lowerCamelCase_ : Dict = json.loads(line) if line.get('''nodeid''', '''''') != "": lowerCamelCase_ : Any = line['''nodeid'''] if line.get('''duration''', None) is not None: lowerCamelCase_ : Any = f"""{line["duration"]:.4f}""" if line.get('''outcome''', '''''') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('''_''')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) lowerCamelCase_ : List[Any] = [] log.unlink() lowerCamelCase_ : str = '''''' lowerCamelCase_ : Dict = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" lowerCamelCase_ : Any = [] lowerCamelCase_ : Tuple = {} for test in failed_tests: lowerCamelCase_ : Optional[int] = test[0].split('''::''') lowerCamelCase_ : List[Any] = data[0].split('''/''')[-1] if data[0] not in filesafailed: lowerCamelCase_ : str = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) lowerCamelCase_ : List[Any] = [test[0] for test in failed_table] lowerCamelCase_ : List[str] = list(set(files)) # Count number of instances in failed_tests lowerCamelCase_ : Tuple = [] for file in individual_files: table.append([file, len(filesafailed[file])]) lowerCamelCase_ : List[Any] = tabulate( table, headers=['''Test Location''', '''Num Failed'''], tablefmt=hf_table_format, stralign='''right''', ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3000: lowerCamelCase_ : Tuple = '''Too many failed tests, please see the full report in the Action results.''' lowerCamelCase_ : Optional[Any] = len(err) + 10 lowerCamelCase_ : Union[str, Any] = message[: 3000 - offset] + f"""\n...\n```\n{err}""" print(f"""### {message}""") else: lowerCamelCase_ : Union[str, Any] = '''No failed tests! 🤗''' print(f"""## {message}""") payload.append(no_error_payload) if os.environ.get('''TEST_TYPE''', '''''') != "": from slack_sdk import WebClient lowerCamelCase_ : Tuple = WebClient(token=os.environ['''SLACK_API_TOKEN''']) if message != "No failed tests! 🤗": lowerCamelCase_ : Dict = { '''type''': '''section''', '''text''': { '''type''': '''mrkdwn''', '''text''': message, }, } payload.append(md_report) lowerCamelCase_ : List[Any] = { '''type''': '''section''', '''text''': { '''type''': '''mrkdwn''', '''text''': '''*For more details:*''', }, '''accessory''': { '''type''': '''button''', '''text''': { '''type''': '''plain_text''', '''text''': '''Check Action results''', '''emoji''': True, }, '''url''': f"""https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } payload.append(action_button) lowerCamelCase_ : List[Any] = { '''type''': '''context''', '''elements''': [ { '''type''': '''plain_text''', '''text''': f"""Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}""", } ], } payload.append(date_report) lowerCamelCase_ : Union[str, Any] = client.chat_postMessage(channel='''#accelerate-ci-daily''', text=message, blocks=payload) lowerCamelCase_ : List[str] = response.data['''ts'''] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name lowerCamelCase_ : List[Any] = '''''' for i, row in enumerate(test_failures): if row[0] != test_class: lowerCamelCase_ : List[str] = row[0] else: lowerCamelCase_ : Tuple = '''''' lowerCamelCase_ : Any = { '''type''': '''section''', '''text''': { '''type''': '''mrkdwn''', '''text''': f"""Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```""", }, } client.chat_postMessage( channel='''#accelerate-ci-daily''', thread_ts=ts, blocks=[payload], )
700
'''simple docstring''' import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger lowerCamelCase_ : Any = get_logger(__name__) class _SCREAMING_SNAKE_CASE ( enum.Enum ): '''simple docstring''' __a : Tuple = "all_checks" __a : List[Any] = "basic_checks" __a : Dict = "no_checks" class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __magic_name__( _A , _A , _A=None ): '''simple docstring''' if expected_checksums is None: logger.info("""Unable to verify checksums.""" ) return if len(set(_A ) - set(_A ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(_A ) - set(_A ) ) ) if len(set(_A ) - set(_A ) ) > 0: raise UnexpectedDownloadedFile(str(set(_A ) - set(_A ) ) ) UpperCamelCase__ = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] UpperCamelCase__ = """ for """ + verification_name if verification_name is not None else """""" if len(_A ) > 0: raise NonMatchingChecksumError( f"Checksums didn't match{for_verification_name}:\n" f"{bad_urls}\n" """Set `verification_mode='no_checks'` to skip checksums verification and ignore this error""" ) logger.info("""All the checksums matched successfully""" + for_verification_name ) class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __magic_name__( _A , _A ): '''simple docstring''' if expected_splits is None: logger.info("""Unable to verify splits sizes.""" ) return if len(set(_A ) - set(_A ) ) > 0: raise ExpectedMoreSplits(str(set(_A ) - set(_A ) ) ) if len(set(_A ) - set(_A ) ) > 0: raise UnexpectedSplits(str(set(_A ) - set(_A ) ) ) UpperCamelCase__ = [ {"""expected""": expected_splits[name], """recorded""": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_A ) > 0: raise NonMatchingSplitsSizesError(str(_A ) ) logger.info("""All the splits matched successfully.""" ) def __magic_name__( _A , _A = True ): '''simple docstring''' if record_checksum: UpperCamelCase__ = shaaaa() with open(_A , """rb""" ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B"""""" ): m.update(_A ) UpperCamelCase__ = m.hexdigest() else: UpperCamelCase__ = None return {"num_bytes": os.path.getsize(_A ), "checksum": checksum} def __magic_name__( _A ): '''simple docstring''' if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
265
0
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml __magic_name__ : Optional[Any] = logging.get_logger(__name__) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): def run_func(SCREAMING_SNAKE_CASE ): @wraps(SCREAMING_SNAKE_CASE ) def run_in_eager_mode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ): return func(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @wraps(SCREAMING_SNAKE_CASE ) @tf.function(experimental_compile=SCREAMING_SNAKE_CASE ) def run_in_graph_mode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ): return func(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if do_eager_mode is True: if use_xla is not False: raise ValueError( """Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.""" ) return run_in_eager_mode else: return run_in_graph_mode return run_func def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Optional[int] = random.Random() UpperCamelCase : Tuple = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(SCREAMING_SNAKE_CASE , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class lowercase__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase : TensorFlowBenchmarkArguments __lowerCAmelCase : PretrainedConfig __lowerCAmelCase : str = "TensorFlow" @property def _a ( self ): '''simple docstring''' return tf.__version__ def _a ( self , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) UpperCamelCase : Optional[int] = self._prepare_inference_func(_A , _A , _A ) return self._measure_speed(_inference ) def _a ( self , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Dict = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) UpperCamelCase : str = self._prepare_train_func(_A , _A , _A ) return self._measure_speed(_train ) def _a ( self , _A , _A , _A ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _A ) UpperCamelCase : int = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) UpperCamelCase : Dict = self._prepare_inference_func(_A , _A , _A ) return self._measure_memory(_inference ) def _a ( self , _A , _A , _A ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _A ) UpperCamelCase : List[str] = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) UpperCamelCase : Any = self._prepare_train_func(_A , _A , _A ) return self._measure_memory(_train ) def _a ( self , _A , _A , _A ): '''simple docstring''' UpperCamelCase : List[str] = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError("""Mixed precision is currently not supported.""" ) UpperCamelCase : Optional[int] = ( hasattr(_A , """architectures""" ) and isinstance(config.architectures , _A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: UpperCamelCase : List[str] = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model UpperCamelCase : Optional[int] = __import__("""transformers""" , fromlist=[model_class] ) UpperCamelCase : str = getattr(_A , _A ) UpperCamelCase : Dict = model_cls(_A ) except ImportError: raise ImportError( f"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" """ set `--only_pretrain_model` or `args.only_pretrain_model=True`.""" ) else: UpperCamelCase : Optional[int] = TF_MODEL_MAPPING[config.__class__](_A ) # encoder-decoder has vocab size saved differently UpperCamelCase : Optional[Any] = config.vocab_size if hasattr(_A , """vocab_size""" ) else config.encoder.vocab_size UpperCamelCase : Dict = random_input_ids(_A , _A , _A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(_A , decoder_input_ids=_A , training=_A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(_A , training=_A ) UpperCamelCase : str = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def _a ( self , _A , _A , _A ): '''simple docstring''' UpperCamelCase : Tuple = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError("""Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.""" ) if self.args.fpaa: raise NotImplementedError("""Mixed precision is currently not supported.""" ) UpperCamelCase : int = ( hasattr(_A , """architectures""" ) and isinstance(config.architectures , _A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: UpperCamelCase : Optional[int] = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model UpperCamelCase : Any = __import__("""transformers""" , fromlist=[model_class] ) UpperCamelCase : Optional[int] = getattr(_A , _A ) UpperCamelCase : Union[str, Any] = model_cls(_A ) except ImportError: raise ImportError( f"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" """ set `--only_pretrain_model` or `args.only_pretrain_model=True`.""" ) else: UpperCamelCase : str = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_A ) # encoder-decoder has vocab size saved differently UpperCamelCase : str = config.vocab_size if hasattr(_A , """vocab_size""" ) else config.encoder.vocab_size UpperCamelCase : Union[str, Any] = random_input_ids(_A , _A , _A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): UpperCamelCase : str = model(_A , decoder_input_ids=_A , labels=_A , training=_A )[0] UpperCamelCase : Any = tf.gradients(_A , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): UpperCamelCase : List[str] = model(_A , labels=_A , training=_A )[0] UpperCamelCase : int = tf.gradients(_A , model.trainable_variables ) return gradients UpperCamelCase : Tuple = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def _a ( self , _A ): '''simple docstring''' with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info("""Do inference on TPU. Running model 5 times to stabilize compilation""" ) timeit.repeat(_A , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average UpperCamelCase : int = timeit.repeat( _A , repeat=self.args.repeat , number=1_0 , ) return min(_A ) / 10.0 except ResourceExhaustedError as e: self.print_fn(f"""Doesn't fit on GPU. {e}""" ) def _a ( self , _A ): '''simple docstring''' logger.info( """Note that TensorFlow allocates more memory than """ """it might need to speed up computation. """ """The memory reported here corresponds to the memory """ """reported by `nvidia-smi`, which can vary depending """ """on total available memory on the GPU that is used.""" ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( """`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory""" """ consumption line by line.""" ) UpperCamelCase : List[str] = start_memory_tracing("""transformers""" ) if self.args.is_tpu: # tpu raise NotImplementedError( """Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking""" """ with `args.memory=False`""" ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( """py3nvml not installed, we won't log GPU memory usage. """ """Install py3nvml (pip install py3nvml) to log information about GPU.""" ) UpperCamelCase : str = """N/A""" else: logger.info( """Measuring total GPU usage on GPU device. Make sure to not have additional processes""" """ running on the same GPU.""" ) # init nvml nvml.nvmlInit() func() UpperCamelCase : Dict = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) UpperCamelCase : List[str] = nvml.nvmlDeviceGetMemoryInfo(_A ) UpperCamelCase : Union[str, Any] = meminfo.used UpperCamelCase : Tuple = Memory(_A ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( """When enabling line by line tracing, the max peak memory for CPU is inaccurate in""" """ TensorFlow.""" ) UpperCamelCase : Dict = None else: UpperCamelCase : List[Any] = measure_peak_memory_cpu(_A ) UpperCamelCase : Dict = Memory(_A ) if isinstance(_A , _A ) else memory_bytes if self.args.trace_memory_line_by_line: UpperCamelCase : List[str] = stop_memory_tracing(_A ) if memory is None: UpperCamelCase : str = summary.total else: UpperCamelCase : Tuple = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f"""Doesn't fit on GPU. {e}""" ) return "N/A", None
102
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __magic_name__ : Any = """pt""" elif is_tf_available(): __magic_name__ : Optional[Any] = """tf""" else: __magic_name__ : int = """jax""" class lowercase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __lowerCAmelCase : Any = PerceiverTokenizer __lowerCAmelCase : int = False def _a ( self ): '''simple docstring''' super().setUp() UpperCamelCase : List[Any] = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _a ( self ): '''simple docstring''' return PerceiverTokenizer.from_pretrained("""deepmind/language-perceiver""" ) def _a ( self , **_A ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **_A ) def _a ( self , _A , _A=False , _A=2_0 , _A=5 ): '''simple docstring''' UpperCamelCase : Tuple = [] for i in range(len(_A ) ): try: UpperCamelCase : List[str] = tokenizer.decode([i] , clean_up_tokenization_spaces=_A ) except UnicodeDecodeError: pass toks.append((i, tok) ) UpperCamelCase : Dict = list(filter(lambda _A : re.match(r"""^[ a-zA-Z]+$""" , t[1] ) , _A ) ) UpperCamelCase : List[str] = list(filter(lambda _A : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_A ) , _A ) ) if max_length is not None and len(_A ) > max_length: UpperCamelCase : int = toks[:max_length] if min_length is not None and len(_A ) < min_length and len(_A ) > 0: while len(_A ) < min_length: UpperCamelCase : List[str] = toks + toks # toks_str = [t[1] for t in toks] UpperCamelCase : Any = [t[0] for t in toks] # Ensure consistency UpperCamelCase : List[str] = tokenizer.decode(_A , clean_up_tokenization_spaces=_A ) if " " not in output_txt and len(_A ) > 1: UpperCamelCase : Optional[Any] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_A ) + """ """ + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_A ) ) if with_prefix_space: UpperCamelCase : Dict = """ """ + output_txt UpperCamelCase : List[Any] = tokenizer.encode(_A , add_special_tokens=_A ) return output_txt, output_ids def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.perceiver_tokenizer UpperCamelCase : str = """Unicode €.""" UpperCamelCase : Dict = tokenizer(_A ) UpperCamelCase : Optional[Any] = [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5] self.assertEqual(encoded["""input_ids"""] , _A ) # decoding UpperCamelCase : Optional[int] = tokenizer.decode(_A ) self.assertEqual(_A , """[CLS]Unicode €.[SEP]""" ) UpperCamelCase : str = tokenizer("""e è é ê ë""" ) UpperCamelCase : str = [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5] self.assertEqual(encoded["""input_ids"""] , _A ) # decoding UpperCamelCase : Any = tokenizer.decode(_A ) self.assertEqual(_A , """[CLS]e è é ê ë[SEP]""" ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë""" ) ) , """[CLS]e è é ê ë[SEP]""" ) def _a ( self ): '''simple docstring''' UpperCamelCase : Optional[int] = self.perceiver_tokenizer UpperCamelCase : Optional[Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] # fmt: off UpperCamelCase : List[Any] = [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0] # fmt: on UpperCamelCase : Dict = tokenizer(_A , padding=_A , return_tensors=_A ) self.assertIsInstance(_A , _A ) if FRAMEWORK != "jax": UpperCamelCase : Dict = list(batch.input_ids.numpy()[0] ) else: UpperCamelCase : Optional[int] = list(batch.input_ids.tolist()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 3_8) , batch.input_ids.shape ) self.assertEqual((2, 3_8) , batch.attention_mask.shape ) def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.perceiver_tokenizer UpperCamelCase : Optional[int] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] UpperCamelCase : Any = tokenizer(_A , padding=_A , return_tensors=_A ) # check if input_ids are returned and no decoder_input_ids self.assertIn("""input_ids""" , _A ) self.assertIn("""attention_mask""" , _A ) self.assertNotIn("""decoder_input_ids""" , _A ) self.assertNotIn("""decoder_attention_mask""" , _A ) def _a ( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.perceiver_tokenizer UpperCamelCase : int = [ """Summary of the text.""", """Another summary.""", ] UpperCamelCase : int = tokenizer( text_target=_A , max_length=3_2 , padding="""max_length""" , truncation=_A , return_tensors=_A ) self.assertEqual(3_2 , targets["""input_ids"""].shape[1] ) def _a ( self ): '''simple docstring''' UpperCamelCase : Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test UpperCamelCase : Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc UpperCamelCase : int = tempfile.mkdtemp() UpperCamelCase : Tuple = """ He is very happy, UNwant\u00E9d,running""" UpperCamelCase : Dict = tokenizer.encode(_A , add_special_tokens=_A ) tokenizer.save_pretrained(_A ) UpperCamelCase : Any = tokenizer.__class__.from_pretrained(_A ) UpperCamelCase : Tuple = after_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) shutil.rmtree(_A ) UpperCamelCase : Union[str, Any] = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc UpperCamelCase : List[Any] = tempfile.mkdtemp() UpperCamelCase : Union[str, Any] = """ He is very happy, UNwant\u00E9d,running""" tokenizer.add_tokens(["""bim""", """bambam"""] ) UpperCamelCase : int = tokenizer.additional_special_tokens additional_special_tokens.append("""new_additional_special_token""" ) tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} ) UpperCamelCase : List[str] = tokenizer.encode(_A , add_special_tokens=_A ) tokenizer.save_pretrained(_A ) UpperCamelCase : List[str] = tokenizer.__class__.from_pretrained(_A ) UpperCamelCase : Tuple = after_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) self.assertIn("""new_additional_special_token""" , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) UpperCamelCase : Any = tokenizer.__class__.from_pretrained(_A , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(_A ) def _a ( self ): '''simple docstring''' UpperCamelCase : int = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_A ) with open(os.path.join(_A , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file: UpperCamelCase : Union[str, Any] = json.load(_A ) with open(os.path.join(_A , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file: UpperCamelCase : List[Any] = json.load(_A ) UpperCamelCase : Optional[int] = [f"""<extra_id_{i}>""" for i in range(1_2_5 )] UpperCamelCase : List[Any] = added_tokens_extra_ids + [ """an_additional_special_token""" ] UpperCamelCase : int = added_tokens_extra_ids + [ """an_additional_special_token""" ] with open(os.path.join(_A , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(_A , _A ) with open(os.path.join(_A , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile: json.dump(_A , _A ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files UpperCamelCase : Tuple = tokenizer_class.from_pretrained( _A , ) self.assertIn( """an_additional_special_token""" , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ["""an_additional_special_token"""] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained UpperCamelCase : List[str] = added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token""" , lstrip=_A )] UpperCamelCase : Optional[Any] = tokenizer_class.from_pretrained( _A , additional_special_tokens=_A , ) self.assertIn("""a_new_additional_special_token""" , tokenizer.additional_special_tokens ) self.assertEqual( ["""a_new_additional_special_token"""] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""] ) ) , ) def _a ( self ): '''simple docstring''' UpperCamelCase : Dict = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([1_7_8] ) , """�""" ) def _a ( self ): '''simple docstring''' pass def _a ( self ): '''simple docstring''' pass def _a ( self ): '''simple docstring''' pass def _a ( self ): '''simple docstring''' pass def _a ( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.get_tokenizers(fast=_A , do_lower_case=_A ) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): UpperCamelCase : Optional[Any] = ["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""] UpperCamelCase : Dict = tokenizer.convert_tokens_to_string(_A ) self.assertIsInstance(_A , _A )
102
1
from __future__ import annotations def UpperCAmelCase__ ( lowercase__ ) -> int: __lowercase = len(UpperCamelCase__ ) // 2 # choose the middle 3 elements __lowercase = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
720
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json", # See all SEW models at https://huggingface.co/models?filter=sew } class _lowerCAmelCase ( _UpperCAmelCase ): """simple docstring""" lowercase__ : Union[str, Any] = """sew""" def __init__( self : List[Any] , lowercase : int=32 , lowercase : List[str]=768 , lowercase : Dict=12 , lowercase : str=12 , lowercase : str=3_072 , lowercase : Optional[int]=2 , lowercase : List[str]="gelu" , lowercase : List[str]=0.1 , lowercase : Tuple=0.1 , lowercase : Dict=0.1 , lowercase : Any=0.0 , lowercase : Dict=0.1 , lowercase : Optional[int]=0.1 , lowercase : List[str]=0.02 , lowercase : Dict=1E-5 , lowercase : Tuple="group" , lowercase : int="gelu" , lowercase : Any=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , lowercase : Optional[int]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , lowercase : Any=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , lowercase : List[str]=False , lowercase : Tuple=128 , lowercase : int=16 , lowercase : Union[str, Any]=True , lowercase : List[str]=0.05 , lowercase : Optional[int]=10 , lowercase : Any=2 , lowercase : Optional[Any]=0.0 , lowercase : Optional[Any]=10 , lowercase : int=0 , lowercase : Optional[int]="mean" , lowercase : List[Any]=False , lowercase : str=False , lowercase : int=256 , lowercase : str=0 , lowercase : List[Any]=1 , lowercase : List[Any]=2 , **lowercase : List[Any] , ) -> Optional[Any]: """simple docstring""" super().__init__(**lowercase , pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase ) __lowercase = hidden_size __lowercase = feat_extract_norm __lowercase = feat_extract_activation __lowercase = list(lowercase ) __lowercase = list(lowercase ) __lowercase = list(lowercase ) __lowercase = conv_bias __lowercase = num_conv_pos_embeddings __lowercase = num_conv_pos_embedding_groups __lowercase = len(self.conv_dim ) __lowercase = num_hidden_layers __lowercase = intermediate_size __lowercase = squeeze_factor __lowercase = hidden_act __lowercase = num_attention_heads __lowercase = hidden_dropout __lowercase = attention_dropout __lowercase = activation_dropout __lowercase = feat_proj_dropout __lowercase = final_dropout __lowercase = layerdrop __lowercase = layer_norm_eps __lowercase = initializer_range __lowercase = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F"but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)" F"= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __lowercase = apply_spec_augment __lowercase = mask_time_prob __lowercase = mask_time_length __lowercase = mask_time_min_masks __lowercase = mask_feature_prob __lowercase = mask_feature_length __lowercase = mask_feature_min_masks # ctc loss __lowercase = ctc_loss_reduction __lowercase = ctc_zero_infinity # sequence classification __lowercase = use_weighted_layer_sum __lowercase = classifier_proj_size @property def snake_case__ ( self : Dict ) -> str: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
634
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor __snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( lowercase ): """simple docstring""" def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> None: warnings.warn( '''The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use DeformableDetrImageProcessor instead.''' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
658
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __snake_case = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
1
'''simple docstring''' 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
459
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __lowerCamelCase : Any = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" __lowerCamelCase : Dict = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" __lowerCamelCase : List[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): def UpperCAmelCase__ (self : List[str] ) -> Union[str, Any]: if version.parse(scb.__version__ ) < version.parse("1.4.12" ): raise ImportWarning( "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n" "You can install it with `pip install \"sacrebleu>=1.4.12\"`." ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/mjpost/sacreBLEU#chrf--chrf" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/mjpost/sacreBLEU#chrf--chrf"] , reference_urls=[ "https://github.com/m-popovic/chrF", ] , ) def UpperCAmelCase__ (self : Tuple , A__ : Dict , A__ : Tuple , A__ : int = CHRF.CHAR_ORDER , A__ : int = CHRF.WORD_ORDER , A__ : int = CHRF.BETA , A__ : bool = False , A__ : bool = False , A__ : bool = False , ) -> List[str]: lowercase = len(references[0] ) if any(len(A__ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) lowercase = [[refs[i] for refs in references] for i in range(A__ )] lowercase = CHRF(A__ , A__ , A__ , A__ , A__ , A__ ) lowercase = sb_chrf.corpus_score(A__ , A__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
459
1
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = (EulerDiscreteScheduler,) lowerCAmelCase__ = 10 def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Any ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = { """num_train_timesteps""": 1_100, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", } config.update(**__SCREAMING_SNAKE_CASE ) return config def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__SCREAMING_SNAKE_CASE , beta_end=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 10.0807 ) < 1E-2 assert abs(result_mean.item() - 0.0131 ) < 1E-3 def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config(prediction_type="""v_prediction""" ) __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 0.0002 ) < 1E-2 assert abs(result_mean.item() - 2.2_676E-06 ) < 1E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 10.0807 ) < 1E-2 assert abs(result_mean.item() - 0.0131 ) < 1E-3 def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE , use_karras_sigmas=__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 124.52299499511719 ) < 1E-2 assert abs(result_mean.item() - 0.16213932633399963 ) < 1E-3
627
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ShapEImgaImgPipeline lowerCAmelCase__ = ["image"] lowerCAmelCase__ = ["image"] lowerCAmelCase__ = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] lowerCAmelCase__ = False @property def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self : str ) -> int: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" return 8 @property def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) __SCREAMING_SNAKE_CASE = CLIPVisionModel(__SCREAMING_SNAKE_CASE ) return model @property def UpperCAmelCase__ ( self : Any ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPImageProcessor( crop_size=224 , do_center_crop=__SCREAMING_SNAKE_CASE , do_normalize=__SCREAMING_SNAKE_CASE , do_resize=__SCREAMING_SNAKE_CASE , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } __SCREAMING_SNAKE_CASE = PriorTransformer(**__SCREAMING_SNAKE_CASE ) return model @property def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } __SCREAMING_SNAKE_CASE = ShapERenderer(**__SCREAMING_SNAKE_CASE ) return model def UpperCAmelCase__ ( self : str ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_prior __SCREAMING_SNAKE_CASE = self.dummy_image_encoder __SCREAMING_SNAKE_CASE = self.dummy_image_processor __SCREAMING_SNAKE_CASE = self.dummy_renderer __SCREAMING_SNAKE_CASE = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1_024 , prediction_type="""sample""" , use_karras_sigmas=__SCREAMING_SNAKE_CASE , clip_sample=__SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) __SCREAMING_SNAKE_CASE = { """prior""": prior, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : str=0 ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 64, 64) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe(**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = output.images[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : str ) -> Dict: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = torch_device == """cpu""" __SCREAMING_SNAKE_CASE = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__SCREAMING_SNAKE_CASE , relax_max_difference=__SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: __SCREAMING_SNAKE_CASE = batch_size * [inputs[key]] __SCREAMING_SNAKE_CASE = pipe(**__SCREAMING_SNAKE_CASE , num_images_per_prompt=__SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) __SCREAMING_SNAKE_CASE = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
627
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase :Any = StableDiffusionXLImgaImgPipeline lowerCamelCase :List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} lowerCamelCase :List[str] = PipelineTesterMixin.required_optional_params - {'''latents'''} lowerCamelCase :Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCamelCase :Optional[int] = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase :Dict = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase ( self ) -> Any: torch.manual_seed(0 ) _A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=lowerCAmelCase_ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) _A = EulerDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) _A = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_28 , ) torch.manual_seed(0 ) _A = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="""gelu""" , projection_dim=32 , ) _A = CLIPTextModel(lowerCAmelCase_ ) _A = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=lowerCAmelCase_ ) _A = CLIPTextModelWithProjection(lowerCAmelCase_ ) _A = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=lowerCAmelCase_ ) _A = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Optional[Any]: _A = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCAmelCase_ ) ).to(lowerCAmelCase_ ) _A = image / 2 + 0.5 if str(lowerCAmelCase_ ).startswith("""mps""" ): _A = torch.manual_seed(lowerCAmelCase_ ) else: _A = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def UpperCAmelCase ( self ) -> int: _A = """cpu""" # ensure determinism for the device-dependent torch.Generator _A = self.get_dummy_components() _A = StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_ ) _A = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A = self.get_dummy_inputs(lowerCAmelCase_ ) _A = sd_pipe(**lowerCAmelCase_ ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _A = np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase ( self ) -> str: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def UpperCAmelCase ( self ) -> Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def UpperCAmelCase ( self ) -> Optional[Any]: pass def UpperCAmelCase ( self ) -> int: _A = self.get_dummy_components() _A = StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_ ) _A = sd_pipe.to(lowerCAmelCase_ ) _A = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) # forward without prompt embeds _A = self.get_dummy_inputs(lowerCAmelCase_ ) _A = 3 * ["""this is a negative prompt"""] _A = negative_prompt _A = 3 * [inputs["""prompt"""]] _A = sd_pipe(**lowerCAmelCase_ ) _A = output.images[0, -3:, -3:, -1] # forward with prompt embeds _A = self.get_dummy_inputs(lowerCAmelCase_ ) _A = 3 * ["""this is a negative prompt"""] _A = 3 * [inputs.pop("""prompt""" )] ( ( _A ) , ( _A ) , ( _A ) , ( _A ) , ) = sd_pipe.encode_prompt(lowerCAmelCase_ , negative_prompt=lowerCAmelCase_ ) _A = sd_pipe( **lowerCAmelCase_ , prompt_embeds=lowerCAmelCase_ , negative_prompt_embeds=lowerCAmelCase_ , pooled_prompt_embeds=lowerCAmelCase_ , negative_pooled_prompt_embeds=lowerCAmelCase_ , ) _A = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_="cpu" , lowerCAmelCase_=torch.floataa , lowerCAmelCase_=0 ) -> Tuple: _A = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) _A = np.random.RandomState(lowerCAmelCase_ ).standard_normal((1, 4, 64, 64) ) _A = torch.from_numpy(lowerCAmelCase_ ).to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) _A = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def UpperCAmelCase ( self ) -> int: _A = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _A = self.get_inputs(lowerCAmelCase_ ) _A = pipe(**lowerCAmelCase_ ).images _A = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) _A = np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
83
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _SCREAMING_SNAKE_CASE = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
83
1
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __UpperCAmelCase ( _lowerCamelCase ): '''simple docstring''' lowercase : str = "Speech2TextFeatureExtractor" lowercase : Optional[Any] = "Speech2TextTokenizer" def __init__( self , _A , _A ): '''simple docstring''' super().__init__(UpperCamelCase_ , UpperCamelCase_ ) _SCREAMING_SNAKE_CASE =self.feature_extractor _SCREAMING_SNAKE_CASE =False def __call__( self , *_A , **_A ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*UpperCamelCase_ , **UpperCamelCase_ ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) _SCREAMING_SNAKE_CASE =kwargs.pop('''raw_speech''' ) else: _SCREAMING_SNAKE_CASE =kwargs.pop('''audio''' , UpperCamelCase_ ) _SCREAMING_SNAKE_CASE =kwargs.pop('''sampling_rate''' , UpperCamelCase_ ) _SCREAMING_SNAKE_CASE =kwargs.pop('''text''' , UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: _SCREAMING_SNAKE_CASE =args[0] _SCREAMING_SNAKE_CASE =args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: _SCREAMING_SNAKE_CASE =self.feature_extractor(UpperCamelCase_ , *UpperCamelCase_ , sampling_rate=UpperCamelCase_ , **UpperCamelCase_ ) if text is not None: _SCREAMING_SNAKE_CASE =self.tokenizer(UpperCamelCase_ , **UpperCamelCase_ ) if text is None: return inputs elif audio is None: return encodings else: _SCREAMING_SNAKE_CASE =encodings["input_ids"] return inputs def UpperCamelCase_ ( self , *_A , **_A ): '''simple docstring''' return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def UpperCamelCase_ ( self , *_A , **_A ): '''simple docstring''' return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @contextmanager def UpperCamelCase_ ( self ): '''simple docstring''' warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =self.tokenizer yield _SCREAMING_SNAKE_CASE =self.feature_extractor _SCREAMING_SNAKE_CASE =False
255
'''simple docstring''' import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py _a : Tuple = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. _a : int = direct_transformers_import(PATH_TO_TRANSFORMERS) _a : Dict = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` _a : int = re.compile(R"\[(.+?)\]\((https://huggingface\.co/.+?)\)") _a : Any = { "DecisionTransformerConfig", "EncoderDecoderConfig", "MusicgenConfig", "RagConfig", "SpeechEncoderDecoderConfig", "TimmBackboneConfig", "VisionEncoderDecoderConfig", "VisionTextDualEncoderConfig", "LlamaConfig", } def _lowercase ( lowerCamelCase__ ) -> Tuple: """simple docstring""" __UpperCAmelCase : Any = None # source code of `config_class` __UpperCAmelCase : Any = inspect.getsource(lowerCamelCase__ ) __UpperCAmelCase : List[Any] = _re_checkpoint.findall(lowerCamelCase__ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("/" ): __UpperCAmelCase : List[str] = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link __UpperCAmelCase : List[str] = f"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: __UpperCAmelCase : Union[str, Any] = ckpt_name break return checkpoint def _lowercase ( ) -> List[Any]: """simple docstring""" __UpperCAmelCase : Optional[int] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue __UpperCAmelCase : List[Any] = get_checkpoint_from_config_class(lowerCamelCase__ ) __UpperCAmelCase : Optional[Any] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: __UpperCAmelCase : Optional[Any] = "\n".join(sorted(lowerCamelCase__ ) ) raise ValueError(f"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
168
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def lowercase__ ( __UpperCamelCase : Callable[[int | float], int | float] , __UpperCamelCase : int | float , __UpperCamelCase : int | float , __UpperCamelCase : int = 100 , ): '''simple docstring''' __lowercase = x_start __lowercase = fnc(__UpperCamelCase ) __lowercase = 0.0 for _ in range(__UpperCamelCase ): # Approximates small segments of curve as linear and solve # for trapezoidal area __lowercase = (x_end - x_start) / steps + xa __lowercase = fnc(__UpperCamelCase ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __lowercase = xa __lowercase = fxa return area if __name__ == "__main__": def lowercase__ ( __UpperCamelCase : Any ): '''simple docstring''' return x**3 + x**2 print('f(x) = x^3 + x^2') print('The area between the curve, x = -5, x = 5 and the x axis is:') snake_case : List[str] = 10 while i <= 100_000: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
339
'''simple docstring''' from __future__ import annotations snake_case : Union[str, Any] = 10 def lowercase__ ( __UpperCamelCase : list[int] ): '''simple docstring''' __lowercase = 1 __lowercase = max(__UpperCamelCase ) while placement <= max_digit: # declare and initialize empty buckets __lowercase = [[] for _ in range(__UpperCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: __lowercase = int((i / placement) % RADIX ) buckets[tmp].append(__UpperCamelCase ) # put each buckets' contents into list_of_ints __lowercase = 0 for b in range(__UpperCamelCase ): for i in buckets[b]: __lowercase = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
339
1
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors snake_case = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = '''sequence-classification''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple ): if type(UpperCAmelCase_ ) == dict: SCREAMING_SNAKE_CASE : List[str] = Namespace(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = glue_output_modes[hparams.task] SCREAMING_SNAKE_CASE : Union[str, Any] = glue_tasks_num_labels[hparams.task] super().__init__(UpperCAmelCase_ , UpperCAmelCase_ , self.mode ) def _A ( self : List[str] , **UpperCAmelCase_ : str ): return self.model(**UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: SCREAMING_SNAKE_CASE : Union[str, Any] = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None SCREAMING_SNAKE_CASE : Union[str, Any] = self(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = outputs[0] SCREAMING_SNAKE_CASE : List[Any] = self.trainer.lr_schedulers[0]["scheduler"] SCREAMING_SNAKE_CASE : List[str] = {"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = self.hparams SCREAMING_SNAKE_CASE : Tuple = processors[args.task]() SCREAMING_SNAKE_CASE : Optional[int] = processor.get_labels() for mode in ["train", "dev"]: SCREAMING_SNAKE_CASE : str = self._feature_file(UpperCAmelCase_ ) if os.path.exists(UpperCAmelCase_ ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , UpperCAmelCase_ ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = ( processor.get_dev_examples(args.data_dir ) if mode == "dev" else processor.get_train_examples(args.data_dir ) ) SCREAMING_SNAKE_CASE : List[str] = convert_examples_to_features( UpperCAmelCase_ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("Saving features into cached file %s" , UpperCAmelCase_ ) torch.save(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : bool = False ): SCREAMING_SNAKE_CASE : Dict = "dev" if mode == "test" else mode SCREAMING_SNAKE_CASE : List[Any] = self._feature_file(UpperCAmelCase_ ) logger.info("Loading features from cached file %s" , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.load(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE : Dict = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) , batch_size=UpperCAmelCase_ , shuffle=UpperCAmelCase_ , ) def _A ( self : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : Dict = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: SCREAMING_SNAKE_CASE : List[str] = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None SCREAMING_SNAKE_CASE : str = self(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = outputs[:2] SCREAMING_SNAKE_CASE : Union[str, Any] = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE : Optional[int] = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _A ( self : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Union[str, Any] = torch.stack([x["val_loss"] for x in outputs] ).mean().detach().cpu().item() SCREAMING_SNAKE_CASE : Tuple = np.concatenate([x["pred"] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": SCREAMING_SNAKE_CASE : List[str] = np.argmax(UpperCAmelCase_ , axis=1 ) elif self.hparams.glue_output_mode == "regression": SCREAMING_SNAKE_CASE : str = np.squeeze(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.concatenate([x["target"] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE : Dict = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE : List[Any] = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE : Any = {**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task , UpperCAmelCase_ , UpperCAmelCase_ )} SCREAMING_SNAKE_CASE : Union[str, Any] = dict(results.items() ) SCREAMING_SNAKE_CASE : Optional[Any] = results return ret, preds_list, out_label_list def _A ( self : Union[str, Any] , UpperCAmelCase_ : list ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self._eval_end(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _A ( self : List[str] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self._eval_end(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _A ( UpperCAmelCase_ : str , UpperCAmelCase_ : int ): BaseTransformer.add_model_specific_args(UpperCAmelCase_ , UpperCAmelCase_ ) parser.add_argument( "--max_seq_length" , default=128 , type=UpperCAmelCase_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--task" , default="" , type=UpperCAmelCase_ , required=UpperCAmelCase_ , help="The GLUE task to run" , ) parser.add_argument( "--gpus" , default=0 , type=UpperCAmelCase_ , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() add_generic_args(lowercase , os.getcwd() ) SCREAMING_SNAKE_CASE : int = GLUETransformer.add_model_specific_args(lowercase , os.getcwd() ) SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: SCREAMING_SNAKE_CASE : List[str] = os.path.join( "./results" , F'''{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}''' , ) os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = GLUETransformer(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = generic_train(lowercase , lowercase ) # Optionally, predict on dev set and write to output_dir if args.do_predict: SCREAMING_SNAKE_CASE : Optional[Any] = sorted(glob.glob(os.path.join(args.output_dir , "checkpoint-epoch=*.ckpt" ) , recursive=lowercase ) ) SCREAMING_SNAKE_CASE : Dict = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(lowercase ) if __name__ == "__main__": main()
62
class snake_case__ : def __init__( self , UpperCamelCase_ , UpperCamelCase_ ) -> Optional[int]: """simple docstring""" a_ : Optional[Any] = name a_ : Union[str, Any] = val def __str__( self ) -> Tuple: """simple docstring""" return f"""{self.__class__.__name__}({self.name}, {self.val})""" def __lt__( self , UpperCamelCase_ ) -> Union[str, Any]: """simple docstring""" return self.val < other.val class snake_case__ : def __init__( self , UpperCamelCase_ ) -> int: """simple docstring""" a_ : Tuple = {} a_ : Optional[int] = {} a_ : Tuple = self.build_heap(UpperCamelCase_ ) def __getitem__( self , UpperCamelCase_ ) -> Any: """simple docstring""" return self.get_value(UpperCamelCase_ ) def A ( self , UpperCamelCase_ ) -> List[Any]: """simple docstring""" return (idx - 1) // 2 def A ( self , UpperCamelCase_ ) -> Optional[Any]: """simple docstring""" return idx * 2 + 1 def A ( self , UpperCamelCase_ ) -> Optional[Any]: """simple docstring""" return idx * 2 + 2 def A ( self , UpperCamelCase_ ) -> List[Any]: """simple docstring""" return self.heap_dict[key] def A ( self , UpperCamelCase_ ) -> Optional[int]: """simple docstring""" a_ : Tuple = len(UpperCamelCase_ ) - 1 a_ : Union[str, Any] = self.get_parent_idx(UpperCamelCase_ ) for idx, i in enumerate(UpperCamelCase_ ): a_ : Tuple = idx a_ : Optional[int] = i.val for i in range(UpperCamelCase_ , -1 , -1 ): self.sift_down(UpperCamelCase_ , UpperCamelCase_ ) return array def A ( self , UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: """simple docstring""" while True: a_ : Tuple = self.get_left_child_idx(UpperCamelCase_ ) # noqa: E741 a_ : Optional[Any] = self.get_right_child_idx(UpperCamelCase_ ) a_ : Union[str, Any] = idx if l < len(UpperCamelCase_ ) and array[l] < array[idx]: a_ : int = l if r < len(UpperCamelCase_ ) and array[r] < array[smallest]: a_ : Optional[int] = r if smallest != idx: a_ , a_ : Optional[int] = array[smallest], array[idx] ( ( a_ ) , ( a_ ) , ) : Tuple = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) a_ : List[str] = smallest else: break def A ( self , UpperCamelCase_ ) -> Any: """simple docstring""" a_ : Union[str, Any] = self.get_parent_idx(UpperCamelCase_ ) while p >= 0 and self.heap[p] > self.heap[idx]: a_ , a_ : Tuple = self.heap[idx], self.heap[p] a_ , a_ : Tuple = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) a_ : Dict = p a_ : Tuple = self.get_parent_idx(UpperCamelCase_ ) def A ( self ) -> Any: """simple docstring""" return self.heap[0] def A ( self ) -> str: """simple docstring""" a_ , a_ : Any = self.heap[-1], self.heap[0] a_ , a_ : List[Any] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) a_ : Any = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def A ( self , UpperCamelCase_ ) -> int: """simple docstring""" self.heap.append(UpperCamelCase_ ) a_ : List[Any] = len(self.heap ) - 1 a_ : Optional[int] = node.val self.sift_up(len(self.heap ) - 1 ) def A ( self ) -> Any: """simple docstring""" return len(self.heap ) == 0 def A ( self , UpperCamelCase_ , UpperCamelCase_ ) -> int: """simple docstring""" assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" a_ : str = new_value a_ : Optional[Any] = new_value self.sift_up(self.idx_of_element[node] ) SCREAMING_SNAKE_CASE : int = Node("R", -1) SCREAMING_SNAKE_CASE : List[str] = Node("B", 6) SCREAMING_SNAKE_CASE : Optional[int] = Node("A", 3) SCREAMING_SNAKE_CASE : Union[str, Any] = Node("X", 1) SCREAMING_SNAKE_CASE : Dict = Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array SCREAMING_SNAKE_CASE : Optional[int] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in my_min_heap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
419
0
from collections import Counter from timeit import timeit def _UpperCAmelCase ( A = "" , ): '''simple docstring''' return sum(c % 2 for c in Counter(input_str.replace(" " , "" ).lower() ).values() ) < 2 def _UpperCAmelCase ( A = "" ): '''simple docstring''' if len(A ) == 0: return True UpperCAmelCase__ =input_str.replace(" " , "" ).lower() # character_freq_dict: Stores the frequency of every character in the input string UpperCAmelCase__ ={} for character in lower_case_input_str: UpperCAmelCase__ =character_freq_dict.get(A , 0 ) + 1 UpperCAmelCase__ =0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def _UpperCAmelCase ( A = "" ): '''simple docstring''' print("\nFor string = " , A , ":" ) print( "> can_string_be_rearranged_as_palindrome_counter()" , "\tans =" , can_string_be_rearranged_as_palindrome_counter(A ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) print( "> can_string_be_rearranged_as_palindrome()" , "\tans =" , can_string_be_rearranged_as_palindrome(A ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) if __name__ == "__main__": UpperCamelCase_ = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) UpperCamelCase_ = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"""{check_str} can {'' if status else 'not '}be rearranged as a palindrome""")
710
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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 torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class snake_case_ : '''simple docstring''' def __init__( self, A_, A_=13, A_=10, A_=3, A_=2, A_=2, A_=2, A_=True, A_=True, A_=32, A_=5, A_=4, A_=37, A_="gelu", A_=0.1, A_=0.1, A_=10, A_=0.02, A_=0.9, A_=None, ) -> int: UpperCAmelCase__ =parent UpperCAmelCase__ =batch_size UpperCAmelCase__ =image_size UpperCAmelCase__ =num_channels UpperCAmelCase__ =patch_size UpperCAmelCase__ =tubelet_size UpperCAmelCase__ =num_frames UpperCAmelCase__ =is_training UpperCAmelCase__ =use_labels UpperCAmelCase__ =hidden_size UpperCAmelCase__ =num_hidden_layers UpperCAmelCase__ =num_attention_heads UpperCAmelCase__ =intermediate_size UpperCAmelCase__ =hidden_act UpperCAmelCase__ =hidden_dropout_prob UpperCAmelCase__ =attention_probs_dropout_prob UpperCAmelCase__ =type_sequence_label_size UpperCAmelCase__ =initializer_range UpperCAmelCase__ =mask_ratio UpperCAmelCase__ =scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame UpperCAmelCase__ =(image_size // patch_size) ** 2 UpperCAmelCase__ =(num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos UpperCAmelCase__ =int(mask_ratio * self.seq_length ) def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase__ =floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ =None if self.use_labels: UpperCAmelCase__ =ids_tensor([self.batch_size], self.type_sequence_label_size ) UpperCAmelCase__ =self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ) -> Union[str, Any]: return VideoMAEConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_frames=self.num_frames, tubelet_size=self.tubelet_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, is_decoder=A_, initializer_range=self.initializer_range, ) def __UpperCAmelCase ( self, A_, A_, A_ ) -> Dict: UpperCAmelCase__ =VideoMAEModel(config=A_ ) model.to(A_ ) model.eval() UpperCAmelCase__ =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self, A_, A_, A_ ) -> Optional[Any]: UpperCAmelCase__ =VideoMAEForPreTraining(A_ ) model.to(A_ ) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch UpperCAmelCase__ =torch.ones((self.num_masks,) ) UpperCAmelCase__ =torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) UpperCAmelCase__ =mask.expand(self.batch_size, -1 ).bool() UpperCAmelCase__ =model(A_, A_ ) # model only returns predictions for masked patches UpperCAmelCase__ =mask.sum().item() UpperCAmelCase__ =3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape, (self.batch_size, num_masked_patches, decoder_num_labels) ) def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase__ =self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ =config_and_inputs UpperCAmelCase__ ={"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case_ ( a, a, unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) __UpperCamelCase = ( {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase__ =VideoMAEModelTester(self ) UpperCAmelCase__ =ConfigTester(self, config_class=A_, has_text_modality=A_, hidden_size=37 ) def __UpperCAmelCase ( self, A_, A_, A_=False ) -> Optional[int]: UpperCAmelCase__ =copy.deepcopy(A_ ) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch UpperCAmelCase__ =torch.ones((self.model_tester.num_masks,) ) UpperCAmelCase__ =torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) UpperCAmelCase__ =mask.expand(self.model_tester.batch_size, -1 ).bool() UpperCAmelCase__ =bool_masked_pos.to(A_ ) if return_labels: if model_class in [ *get_values(A_ ), ]: UpperCAmelCase__ =torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=A_ ) return inputs_dict def __UpperCAmelCase ( self ) -> Optional[Any]: self.config_tester.run_common_tests() @unittest.skip(reason="VideoMAE does not use inputs_embeds" ) def __UpperCAmelCase ( self ) -> Any: pass def __UpperCAmelCase ( self ) -> int: UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ =model_class(A_ ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) UpperCAmelCase__ =model.get_output_embeddings() self.assertTrue(x is None or isinstance(A_, nn.Linear ) ) def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ =model_class(A_ ) UpperCAmelCase__ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ =[*signature.parameters.keys()] UpperCAmelCase__ =["pixel_values"] self.assertListEqual(arg_names[:1], A_ ) def __UpperCAmelCase ( self ) -> Optional[int]: UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*A_ ) @slow def __UpperCAmelCase ( self ) -> int: for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ =VideoMAEModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def __UpperCAmelCase ( self ) -> Tuple: if not self.has_attentions: pass else: UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ =True for model_class in self.all_model_classes: UpperCAmelCase__ =self.model_tester.seq_length - self.model_tester.num_masks UpperCAmelCase__ =( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) UpperCAmelCase__ =True UpperCAmelCase__ =False UpperCAmelCase__ =True UpperCAmelCase__ =model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCAmelCase__ =model(**self._prepare_for_class(A_, A_ ) ) UpperCAmelCase__ =outputs.attentions self.assertEqual(len(A_ ), self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCAmelCase__ =True UpperCAmelCase__ =model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCAmelCase__ =model(**self._prepare_for_class(A_, A_ ) ) UpperCAmelCase__ =outputs.attentions self.assertEqual(len(A_ ), self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ), [self.model_tester.num_attention_heads, seq_len, seq_len], ) UpperCAmelCase__ =len(A_ ) # Check attention is always last and order is fine UpperCAmelCase__ =True UpperCAmelCase__ =True UpperCAmelCase__ =model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCAmelCase__ =model(**self._prepare_for_class(A_, A_ ) ) self.assertEqual(out_len + 1, len(A_ ) ) UpperCAmelCase__ =outputs.attentions self.assertEqual(len(A_ ), self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ), [self.model_tester.num_attention_heads, seq_len, seq_len], ) def __UpperCAmelCase ( self ) -> Dict: def check_hidden_states_output(A_, A_, A_ ): UpperCAmelCase__ =model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCAmelCase__ =model(**self._prepare_for_class(A_, A_ ) ) UpperCAmelCase__ =outputs.hidden_states UpperCAmelCase__ =self.model_tester.num_hidden_layers + 1 self.assertEqual(len(A_ ), A_ ) UpperCAmelCase__ =self.model_tester.seq_length - self.model_tester.num_masks UpperCAmelCase__ =num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ), [seq_length, self.model_tester.hidden_size], ) UpperCAmelCase__ , UpperCAmelCase__ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ =True check_hidden_states_output(A_, A_, A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ =True check_hidden_states_output(A_, A_, A_ ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __UpperCAmelCase ( self ) -> Any: pass def _UpperCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ =hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) UpperCAmelCase__ =np.load(A ) return list(A ) @require_torch @require_vision class snake_case_ ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ) -> Any: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase__ =VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics" ).to( A_ ) UpperCAmelCase__ =self.default_image_processor UpperCAmelCase__ =prepare_video() UpperCAmelCase__ =image_processor(A_, return_tensors="pt" ).to(A_ ) # forward pass with torch.no_grad(): UpperCAmelCase__ =model(**A_ ) # verify the logits UpperCAmelCase__ =torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape, A_ ) UpperCAmelCase__ =torch.tensor([0.36_69, -0.06_88, -0.24_21] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3], A_, atol=1E-4 ) ) @slow def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase__ =VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short" ).to(A_ ) UpperCAmelCase__ =self.default_image_processor UpperCAmelCase__ =prepare_video() UpperCAmelCase__ =image_processor(A_, return_tensors="pt" ).to(A_ ) # add boolean mask, indicating which patches to mask UpperCAmelCase__ =hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos", filename="bool_masked_pos.pt" ) UpperCAmelCase__ =torch.load(A_ ) # forward pass with torch.no_grad(): UpperCAmelCase__ =model(**A_ ) # verify the logits UpperCAmelCase__ =torch.Size([1, 1408, 1536] ) UpperCAmelCase__ =torch.tensor( [[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]], device=A_ ) self.assertEqual(outputs.logits.shape, A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], A_, atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) UpperCAmelCase__ =torch.tensor([0.51_42], device=A_ ) self.assertTrue(torch.allclose(outputs.loss, A_, atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) UpperCAmelCase__ =VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short", norm_pix_loss=A_ ).to( A_ ) with torch.no_grad(): UpperCAmelCase__ =model(**A_ ) UpperCAmelCase__ =torch.tensor(torch.tensor([0.64_69] ), device=A_ ) self.assertTrue(torch.allclose(outputs.loss, A_, atol=1E-4 ) )
510
0
import math def snake_case (__lowercase , __lowercase ) -> float: '''simple docstring''' return math.pow(__lowercase , 2 ) - a def snake_case (__lowercase ) -> float: '''simple docstring''' return 2 * x def snake_case (__lowercase ) -> float: '''simple docstring''' _snake_case : Optional[Any] = 2.0 while start <= a: _snake_case : Union[str, Any] = math.pow(__lowercase , 2 ) return start def snake_case (__lowercase , __lowercase = 9_999 , __lowercase = 0.00000000000001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("math domain error" ) _snake_case : Optional[Any] = get_initial_point(__lowercase ) for _ in range(__lowercase ): _snake_case : List[Any] = value _snake_case : Optional[Any] = value - fx(__lowercase , __lowercase ) / fx_derivative(__lowercase ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
670
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case (__lowercase ) -> Any: '''simple docstring''' if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(__lowercase ): return ext raise Exception( F"""Unable to determine file format from file extension {path}. """ F"""Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}""" ) def snake_case (__lowercase ) -> Any: '''simple docstring''' _snake_case : int = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) _snake_case : List[Any] = try_infer_format_from_ext(args.input ) if args.format == "infer" else args.format _snake_case : Optional[int] = PipelineDataFormat.from_str( format=__lowercase , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(__lowercase , __lowercase ) class lowercase_ ( __snake_case ): def __init__( self , lowercase_ , lowercase_ ): _snake_case : str = nlp _snake_case : str = reader @staticmethod def UpperCamelCase ( lowercase_ ): _snake_case : Dict = parser.add_parser("run" , help="Run a pipeline through the CLI" ) run_parser.add_argument("--task" , choices=get_supported_tasks() , help="Task to run" ) run_parser.add_argument("--input" , type=lowercase_ , help="Path to the file to use for inference" ) run_parser.add_argument("--output" , type=lowercase_ , help="Path to the file that will be used post to write results." ) run_parser.add_argument("--model" , type=lowercase_ , help="Name or path to the model to instantiate." ) run_parser.add_argument("--config" , type=lowercase_ , help="Name or path to the model's config to instantiate." ) run_parser.add_argument( "--tokenizer" , type=lowercase_ , help="Name of the tokenizer to use. (default: same as the model name)" ) run_parser.add_argument( "--column" , type=lowercase_ , help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)" , ) run_parser.add_argument( "--format" , type=lowercase_ , default="infer" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="Input format to read from" , ) run_parser.add_argument( "--device" , type=lowercase_ , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , ) run_parser.add_argument("--overwrite" , action="store_true" , help="Allow overwriting the output file." ) run_parser.set_defaults(func=lowercase_ ) def UpperCamelCase ( self ): _snake_case ,_snake_case : Tuple = self._nlp, [] for entry in self._reader: _snake_case : Optional[Any] = nlp(**lowercase_ ) if self._reader.is_multi_columns else nlp(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): outputs.append(lowercase_ ) else: outputs += output # Saving data if self._nlp.binary_output: _snake_case : str = self._reader.save_binary(lowercase_ ) logger.warning(f"""Current pipeline requires output to be in binary format, saving at {binary_path}""" ) else: self._reader.save(lowercase_ )
670
1
'''simple docstring''' def lowerCamelCase__ ( _A = 50 ): a : int = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"{solution() = }")
195
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, 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 torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a__: def __init__( self : List[str] , __snake_case : Optional[Any] , __snake_case : Any=13 , __snake_case : int=30 , __snake_case : Union[str, Any]=2 , __snake_case : Optional[int]=3 , __snake_case : Dict=True , __snake_case : List[str]=True , __snake_case : Any=32 , __snake_case : List[Any]=5 , __snake_case : List[Any]=4 , __snake_case : Optional[int]=37 , __snake_case : int="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : List[str]=10 , __snake_case : int=0.02 , __snake_case : Optional[int]=3 , __snake_case : Tuple=0.6 , __snake_case : Union[str, Any]=None , ): a : List[str] = parent a : Tuple = batch_size a : Union[str, Any] = image_size a : List[str] = patch_size a : Optional[Any] = num_channels a : Optional[Any] = is_training a : List[Any] = use_labels a : Union[str, Any] = hidden_size a : Dict = num_hidden_layers a : Optional[Any] = num_attention_heads a : Optional[Any] = intermediate_size a : int = hidden_act a : Dict = hidden_dropout_prob a : Optional[Any] = attention_probs_dropout_prob a : Optional[Any] = type_sequence_label_size a : Optional[Any] = initializer_range a : Union[str, Any] = mask_ratio a : Optional[int] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) a : Tuple = (image_size // patch_size) ** 2 a : List[Any] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowercase_ ( self : List[str] ): a : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a : Tuple = None if self.use_labels: a : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : Optional[int] = self.get_config() return config, pixel_values, labels def lowercase_ ( self : str ): return ViTMAEConfig( 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 , mask_ratio=self.mask_ratio , ) def lowercase_ ( self : Dict , __snake_case : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] ): a : Union[str, Any] = ViTMAEModel(config=__snake_case ) model.to(__snake_case ) model.eval() a : Optional[Any] = model(__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self : Optional[Any] , __snake_case : List[str] , __snake_case : Optional[int] , __snake_case : Dict ): a : Dict = ViTMAEForPreTraining(__snake_case ) model.to(__snake_case ) model.eval() a : Dict = model(__snake_case ) a : str = (self.image_size // self.patch_size) ** 2 a : int = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images a : Any = 1 a : Optional[int] = ViTMAEForPreTraining(__snake_case ) model.to(__snake_case ) model.eval() a : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a : Optional[Any] = model(__snake_case ) a : Dict = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowercase_ ( self : Dict ): a : List[str] = self.prepare_config_and_inputs() a , a , a : Any = config_and_inputs a : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () lowercase__ = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def lowercase_ ( self : Tuple ): a : List[str] = ViTMAEModelTester(self ) a : List[str] = ConfigTester(self , config_class=__snake_case , has_text_modality=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='ViTMAE does not use inputs_embeds' ) def lowercase_ ( self : List[str] ): pass def lowercase_ ( self : Dict ): a , a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Optional[Any] = model_class(__snake_case ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__snake_case , nn.Linear ) ) def lowercase_ ( self : List[str] ): a , a : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Any = model_class(__snake_case ) a : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a : int = [*signature.parameters.keys()] a : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __snake_case ) def lowercase_ ( self : Any ): a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowercase_ ( self : List[Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Optional[Any] , __snake_case : Union[str, Any] , __snake_case : Tuple ): # make masks reproducible np.random.seed(2 ) a : Union[str, Any] = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) a : int = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) a : List[Any] = torch.from_numpy(__snake_case ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument a : List[str] = pt_noise super().check_pt_tf_models(__snake_case , __snake_case , __snake_case ) def lowercase_ ( self : Optional[int] ): a , a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Any = model_class(__snake_case ) model.to(__snake_case ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): a : Tuple = model(**self._prepare_for_class(__snake_case , __snake_case ) ) a : List[str] = outputs[0].cpu().numpy() a : str = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__snake_case ) a : Dict = model_class.from_pretrained(__snake_case ) model.to(__snake_case ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): a : int = model(**self._prepare_for_class(__snake_case , __snake_case ) ) # Make sure we don't have nans a : List[Any] = after_outputs[0].cpu().numpy() a : Any = 0 a : Any = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__snake_case , 1e-5 ) @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def lowercase_ ( self : Any ): pass @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def lowercase_ ( self : int ): pass @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' ) def lowercase_ ( self : int ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase_ ( self : Any ): pass @slow def lowercase_ ( self : Dict ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : str = ViTMAEModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def lowerCamelCase__ ( ): a : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a__( unittest.TestCase ): @cached_property def lowercase_ ( self : Union[str, Any] ): return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None @slow def lowercase_ ( self : Union[str, Any] ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) a : Union[str, Any] = ViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ).to(__snake_case ) a : str = self.default_image_processor a : Dict = prepare_img() a : Union[str, Any] = image_processor(images=__snake_case , return_tensors='pt' ).to(__snake_case ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) a : Tuple = ViTMAEConfig() a : Optional[Any] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) a : List[str] = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): a : Tuple = model(**__snake_case , noise=torch.from_numpy(__snake_case ).to(device=__snake_case ) ) # verify the logits a : int = torch.Size((1, 1_96, 7_68) ) self.assertEqual(outputs.logits.shape , __snake_case ) a : Optional[Any] = torch.tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(__snake_case ) , atol=1e-4 ) )
195
1
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() A__: Any = 2 class _a : """simple docstring""" def __init__( self: List[Any] , *, # begin keyword-only arguments __lowerCamelCase: Tuple="<s>" , __lowerCamelCase: List[str]="<pad>" , __lowerCamelCase: str="</s>" , __lowerCamelCase: Tuple="<unk>" , __lowerCamelCase: List[Any]=None , ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__: Any = bos, unk, pad, eos UpperCamelCase__: Tuple = [] UpperCamelCase__: Union[str, Any] = [] UpperCamelCase__: Optional[int] = {} UpperCamelCase__: List[Any] = self.add_symbol(lowerCamelCase__ ) UpperCamelCase__: Optional[int] = self.add_symbol(lowerCamelCase__ ) UpperCamelCase__: str = self.add_symbol(lowerCamelCase__ ) UpperCamelCase__: Optional[int] = self.add_symbol(lowerCamelCase__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(lowerCamelCase__ ) UpperCamelCase__: Tuple = len(self.symbols ) def __eq__( self: int , __lowerCamelCase: str ): '''simple docstring''' return self.indices == other.indices def __getitem__( self: Tuple , __lowerCamelCase: List[str] ): '''simple docstring''' if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self: Any ): '''simple docstring''' return len(self.symbols ) def __contains__( self: List[Any] , __lowerCamelCase: List[str] ): '''simple docstring''' return sym in self.indices @classmethod def UpperCAmelCase_ ( cls: List[Any] , __lowerCamelCase: Optional[Any] ): '''simple docstring''' UpperCamelCase__: str = cls() d.add_from_file(lowerCamelCase__ ) return d def UpperCAmelCase_ ( self: int , __lowerCamelCase: Any , __lowerCamelCase: Any=1 , __lowerCamelCase: Union[str, Any]=False ): '''simple docstring''' if word in self.indices and not overwrite: UpperCamelCase__: Union[str, Any] = self.indices[word] UpperCamelCase__: Optional[Any] = self.count[idx] + n return idx else: UpperCamelCase__: str = len(self.symbols ) UpperCamelCase__: str = idx self.symbols.append(lowerCamelCase__ ) self.count.append(lowerCamelCase__ ) return idx def UpperCAmelCase_ ( self: Optional[int] , __lowerCamelCase: Optional[Any] ): '''simple docstring''' return 0 def UpperCAmelCase_ ( self: int , __lowerCamelCase: Any ): '''simple docstring''' if isinstance(lowerCamelCase__ , lowerCamelCase__ ): try: with open(lowerCamelCase__ , "r" , encoding="utf-8" ) as fd: self.add_from_file(lowerCamelCase__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception("Incorrect encoding detected in {}, please rebuild the dataset".format(lowerCamelCase__ ) ) return UpperCamelCase__: List[Any] = f.readlines() UpperCamelCase__: Dict = self._load_meta(lowerCamelCase__ ) for line in lines[indices_start_line:]: try: UpperCamelCase__ , UpperCamelCase__: Any = line.rstrip().rsplit(" " , 1 ) if field == "#fairseq:overwrite": UpperCamelCase__: List[Any] = True UpperCamelCase__ , UpperCamelCase__: int = line.rsplit(" " , 1 ) else: UpperCamelCase__: List[Any] = False UpperCamelCase__: List[Any] = int(lowerCamelCase__ ) UpperCamelCase__: Optional[Any] = line if word in self and not overwrite: raise RuntimeError( "Duplicate word found when loading Dictionary: \'{}\'. " "Duplicate words can overwrite earlier ones by adding the " "#fairseq:overwrite flag at the end of the corresponding row " "in the dictionary file. If using the Camembert model, please " "download an updated copy of the model file.".format(lowerCamelCase__ ) ) self.add_symbol(lowerCamelCase__ , n=lowerCamelCase__ , overwrite=lowerCamelCase__ ) except ValueError: raise ValueError("Incorrect dictionary format, expected \'<token> <cnt> [flags]\'" ) def lowerCAmelCase_ ( A_): # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} UpperCamelCase__: Optional[Any] = dict((re.sub(R"@@$" ,"" ,lowercase_), v) if k.endswith("@@") else (re.sub(R"$" ,"</w>" ,lowercase_), v) for k, v in d.items()) UpperCamelCase__: Dict = "<s> <pad> </s> <unk>".split() # restore the special tokens for k in keep_keys: del da[F"{k}</w>"] UpperCamelCase__: Union[str, Any] = d[k] # restore return da def lowerCAmelCase_ ( A_ ,A_): # prep if not os.path.exists(lowercase_): raise ValueError(F"path {biogpt_checkpoint_path} does not exist!") os.makedirs(lowercase_ ,exist_ok=lowercase_) print(F"Writing results to {pytorch_dump_folder_path}") # handle various types of models UpperCamelCase__: Tuple = os.path.join(lowercase_ ,"checkpoint.pt") if not os.path.isfile(lowercase_): raise ValueError(F"path to the file {checkpoint_file} does not exist!") UpperCamelCase__: Optional[int] = torch.load(lowercase_ ,map_location="cpu") UpperCamelCase__: List[Any] = chkpt["cfg"]["model"] # dicts UpperCamelCase__: Optional[int] = os.path.join(lowercase_ ,"dict.txt") if not os.path.isfile(lowercase_): raise ValueError(F"path to the file {dict_file} does not exist!") UpperCamelCase__: Union[str, Any] = Dictionary.load(lowercase_) UpperCamelCase__: Optional[Any] = rewrite_dict_keys(src_dict.indices) UpperCamelCase__: Optional[Any] = len(lowercase_) UpperCamelCase__: str = os.path.join(lowercase_ ,VOCAB_FILES_NAMES["vocab_file"]) print(F"Generating {src_vocab_file} of {src_vocab_size} records") with open(lowercase_ ,"w" ,encoding="utf-8") as f: f.write(json.dumps(lowercase_ ,ensure_ascii=lowercase_ ,indent=lowercase_)) # merges_file (bpecodes) UpperCamelCase__: Dict = os.path.join(lowercase_ ,"bpecodes") if not os.path.isfile(lowercase_): raise ValueError(F"path to the file {bpecodes_file} does not exist!") UpperCamelCase__: str = os.path.join(lowercase_ ,VOCAB_FILES_NAMES["merges_file"]) shutil.copyfile(lowercase_ ,lowercase_) # model config UpperCamelCase__: List[str] = os.path.join(lowercase_ ,"config.json") UpperCamelCase__: Tuple = { "activation_dropout": args["activation_dropout"], "architectures": ["BioGptForCausalLM"], "attention_probs_dropout_prob": args["attention_dropout"], "bos_token_id": 0, "eos_token_id": 2, "hidden_act": args["activation_fn"], "hidden_dropout_prob": args["dropout"], "hidden_size": args["decoder_embed_dim"], "initializer_range": 0.02, "intermediate_size": args["decoder_ffn_embed_dim"], "layer_norm_eps": 1e-12, "layerdrop": args["decoder_layerdrop"], "max_position_embeddings": args["max_target_positions"], "model_type": "biogpt", "num_attention_heads": args["decoder_attention_heads"], "num_hidden_layers": args["decoder_layers"], "pad_token_id": 1, "scale_embedding": not args["no_scale_embedding"], "tie_word_embeddings": args["share_decoder_input_output_embed"], "vocab_size": src_vocab_size, } # good hparam defaults to start with print(F"Generating {biogpt_model_config_file}") with open(lowercase_ ,"w" ,encoding="utf-8") as f: f.write(json.dumps(lowercase_ ,ensure_ascii=lowercase_ ,indent=lowercase_)) # tokenizer config UpperCamelCase__: Optional[int] = os.path.join(lowercase_ ,lowercase_) UpperCamelCase__: str = { "bos_token": "<s>", "eos_token": "</s>", "model_max_length": 10_24, "pad_token": "<pad>", "special_tokens_map_file": None, "tokenizer_class": "BioGptTokenizer", "unk_token": "<unk>", } print(F"Generating {biogpt_tokenizer_config_file}") with open(lowercase_ ,"w" ,encoding="utf-8") as f: f.write(json.dumps(lowercase_ ,ensure_ascii=lowercase_ ,indent=lowercase_)) # model UpperCamelCase__: List[str] = chkpt["model"] # remove unneeded keys UpperCamelCase__: Any = [ "decoder.version", ] for k in ignore_keys: model_state_dict.pop(lowercase_ ,lowercase_) UpperCamelCase__: str = list(model_state_dict.keys()) for layer_name in layer_names: if layer_name.endswith("output_projection.weight"): UpperCamelCase__: Optional[int] = model_state_dict.pop(lowercase_) else: UpperCamelCase__: Optional[Any] = model_state_dict.pop(lowercase_) UpperCamelCase__: List[Any] = BioGptConfig.from_pretrained(lowercase_) UpperCamelCase__: int = BioGptForCausalLM(lowercase_) # check that it loads ok model_new.load_state_dict(lowercase_) # save UpperCamelCase__: List[str] = os.path.join(lowercase_ ,lowercase_) print(F"Generating {pytorch_weights_dump_path}") torch.save(lowercase_ ,lowercase_) print("Conversion is done!") if __name__ == "__main__": A__: Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) A__: Tuple = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
380
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''configuration_wav2vec2''': ['''WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Wav2Vec2Config'''], '''feature_extraction_wav2vec2''': ['''Wav2Vec2FeatureExtractor'''], '''processing_wav2vec2''': ['''Wav2Vec2Processor'''], '''tokenization_wav2vec2''': ['''Wav2Vec2CTCTokenizer''', '''Wav2Vec2Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ '''WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Wav2Vec2ForAudioFrameClassification''', '''Wav2Vec2ForCTC''', '''Wav2Vec2ForMaskedLM''', '''Wav2Vec2ForPreTraining''', '''Wav2Vec2ForSequenceClassification''', '''Wav2Vec2ForXVector''', '''Wav2Vec2Model''', '''Wav2Vec2PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] = [ '''TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFWav2Vec2ForCTC''', '''TFWav2Vec2Model''', '''TFWav2Vec2PreTrainedModel''', '''TFWav2Vec2ForSequenceClassification''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : str = [ '''FlaxWav2Vec2ForCTC''', '''FlaxWav2Vec2ForPreTraining''', '''FlaxWav2Vec2Model''', '''FlaxWav2Vec2PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .processing_wavaveca import WavaVecaProcessor from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavaveca import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaForAudioFrameClassification, WavaVecaForCTC, WavaVecaForMaskedLM, WavaVecaForPreTraining, WavaVecaForSequenceClassification, WavaVecaForXVector, WavaVecaModel, WavaVecaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWavaVecaForCTC, TFWavaVecaForSequenceClassification, TFWavaVecaModel, TFWavaVecaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_wavaveca import ( FlaxWavaVecaForCTC, FlaxWavaVecaForPreTraining, FlaxWavaVecaModel, FlaxWavaVecaPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
0
'''simple docstring''' 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 :Optional[int] , lowerCAmelCase__ :Dict[str, int] , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :int = None , lowerCAmelCase__ :int = None ) -> Optional[Any]: '''simple docstring''' super().__init__() snake_case_ : Optional[int] = pad_token_id snake_case_ : List[str] = max_length snake_case_ : Tuple = vocab snake_case_ : int = merges snake_case_ : Tuple = BytePairTokenizer(lowerCAmelCase__ , lowerCAmelCase__ , sequence_length=lowerCAmelCase__ ) @classmethod def _A ( cls :str , lowerCAmelCase__ :GPTaTokenizer , *lowerCAmelCase__ :Optional[Any] , **lowerCAmelCase__ :int ) -> Optional[int]: '''simple docstring''' snake_case_ : Union[str, Any] = [" ".join(lowerCAmelCase__ ) for m in tokenizer.bpe_ranks.keys()] snake_case_ : Optional[Any] = tokenizer.get_vocab() return cls(lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) @classmethod def _A ( cls :str , lowerCAmelCase__ :Union[str, os.PathLike] , *lowerCAmelCase__ :str , **lowerCAmelCase__ :List[str] ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = GPTaTokenizer.from_pretrained(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) return cls.from_tokenizer(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) @classmethod def _A ( cls :Tuple , lowerCAmelCase__ :Optional[int] ) -> Dict: '''simple docstring''' return cls(**lowerCAmelCase__ ) def _A ( self :List[str] ) -> int: '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _A ( self :Dict , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :int = None ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.tf_tokenizer(lowerCAmelCase__ ) snake_case_ : Tuple = tf.ones_like(lowerCAmelCase__ ) if self.pad_token_id is not None: # pad the tokens up to max length snake_case_ : Any = max_length if max_length is not None else self.max_length if max_length is not None: snake_case_, snake_case_ : List[str] = pad_model_inputs( lowerCAmelCase__ , max_seq_length=lowerCAmelCase__ , pad_value=self.pad_token_id ) return {"attention_mask": attention_mask, "input_ids": input_ids}
656
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class A_ (unittest.TestCase ): """simple docstring""" def _A ( self :Any ) -> str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _A ( self :List[Any] ) -> List[str]: '''simple docstring''' snake_case_ : Any = 1 snake_case_ : Dict = 3 snake_case_ : Union[str, Any] = (32, 32) snake_case_ : Optional[int] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCAmelCase__ ) return image @property def _A ( self :Optional[int] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : List[str] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def _A ( self :Dict ) -> Any: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Optional[Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def _A ( self :Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : str = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_006 , ) return RobertaSeriesModelWithTransformation(lowerCAmelCase__ ) @property def _A ( self :Any ) -> str: '''simple docstring''' def extract(*lowerCAmelCase__ :Any , **lowerCAmelCase__ :List[str] ): class A_ : """simple docstring""" def __init__( self :Optional[int] ) -> List[str]: '''simple docstring''' snake_case_ : str = torch.ones([0] ) def _A ( self :int , lowerCAmelCase__ :List[Any] ) -> Tuple: '''simple docstring''' self.pixel_values.to(lowerCAmelCase__ ) return self return Out() return extract def _A ( self :int ) -> Dict: '''simple docstring''' snake_case_ : str = "cpu" # ensure determinism for the device-dependent torch.Generator snake_case_ : str = self.dummy_cond_unet snake_case_ : Optional[int] = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ ) snake_case_ : Dict = self.dummy_vae snake_case_ : Dict = self.dummy_text_encoder snake_case_ : Optional[int] = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) snake_case_ : str = 77 snake_case_ : Any = self.dummy_image.to(lowerCAmelCase__ ) snake_case_ : Tuple = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk snake_case_ : Optional[Any] = AltDiffusionImgaImgPipeline( unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , feature_extractor=self.dummy_extractor , ) snake_case_ : Union[str, Any] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowerCAmelCase__ ) snake_case_ : Optional[Any] = alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) snake_case_ : Dict = "A painting of a squirrel eating a burger" snake_case_ : List[str] = torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) snake_case_ : Dict = alt_pipe( [prompt] , generator=lowerCAmelCase__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=lowerCAmelCase__ , ) snake_case_ : Any = output.images snake_case_ : List[str] = torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) snake_case_ : Optional[Any] = alt_pipe( [prompt] , generator=lowerCAmelCase__ , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=lowerCAmelCase__ , return_dict=lowerCAmelCase__ , )[0] snake_case_ : Tuple = image[0, -3:, -3:, -1] snake_case_ : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case_ : int = np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def _A ( self :int ) -> List[str]: '''simple docstring''' snake_case_ : Union[str, Any] = self.dummy_cond_unet snake_case_ : Union[str, Any] = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ ) snake_case_ : int = self.dummy_vae snake_case_ : List[Any] = self.dummy_text_encoder snake_case_ : int = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) snake_case_ : int = 77 snake_case_ : Dict = self.dummy_image.to(lowerCAmelCase__ ) # put models in fp16 snake_case_ : Optional[Any] = unet.half() snake_case_ : Tuple = vae.half() snake_case_ : List[str] = bert.half() # make sure here that pndm scheduler skips prk snake_case_ : Optional[int] = AltDiffusionImgaImgPipeline( unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , feature_extractor=self.dummy_extractor , ) snake_case_ : List[str] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowerCAmelCase__ ) snake_case_ : Optional[Any] = alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) snake_case_ : List[Any] = "A painting of a squirrel eating a burger" snake_case_ : str = torch.manual_seed(0 ) snake_case_ : Any = alt_pipe( [prompt] , generator=lowerCAmelCase__ , num_inference_steps=2 , output_type="np" , image=lowerCAmelCase__ , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def _A ( self :Optional[int] ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 snake_case_ : str = init_image.resize((760, 504) ) snake_case_ : Optional[Any] = "BAAI/AltDiffusion" snake_case_ : int = AltDiffusionImgaImgPipeline.from_pretrained( lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() snake_case_ : Tuple = "A fantasy landscape, trending on artstation" snake_case_ : int = torch.manual_seed(0 ) snake_case_ : List[str] = pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , strength=0.7_5 , guidance_scale=7.5 , generator=lowerCAmelCase__ , output_type="np" , ) snake_case_ : str = output.images[0] snake_case_ : List[Any] = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) snake_case_ : Tuple = np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class A_ (unittest.TestCase ): """simple docstring""" def _A ( self :Optional[Any] ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self :str ) -> Any: '''simple docstring''' snake_case_ : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) snake_case_ : List[Any] = init_image.resize((768, 512) ) snake_case_ : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) snake_case_ : Any = "BAAI/AltDiffusion" snake_case_ : List[str] = AltDiffusionImgaImgPipeline.from_pretrained( lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() snake_case_ : Tuple = "A fantasy landscape, trending on artstation" snake_case_ : Tuple = torch.manual_seed(0 ) snake_case_ : List[Any] = pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , strength=0.7_5 , guidance_scale=7.5 , generator=lowerCAmelCase__ , output_type="np" , ) snake_case_ : Optional[int] = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
656
1
'''simple docstring''' from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time lowercase__ =Lock() def UpperCamelCase_ ( A__ , A__ , A__ , A__ , A__ , A__ , A__ ): global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(A__ ) process_lock.release() # receive your right neighbor's value process_lock.acquire() a_ = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left a_ = min(A__ , A__ ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(A__ ) process_lock.release() # receive your left neighbor's value process_lock.acquire() a_ = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right a_ = max(A__ , A__ ) # after all swaps are performed, send the values back to main result_pipe[1].send(A__ ) def UpperCamelCase_ ( A__ ): a_ = [] a_ = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop a_ = Pipe() a_ = Pipe() process_array_.append( Process( target=A__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) a_ = temp_rs a_ = temp_rr for i in range(1 , len(A__ ) - 1 ): a_ = Pipe() a_ = Pipe() process_array_.append( Process( target=A__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) a_ = temp_rs a_ = temp_rr process_array_.append( Process( target=A__ , args=( len(A__ ) - 1, arr[len(A__ ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(A__ ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(A__ ) ): a_ = result_pipe[p][0].recv() process_array_[p].join() return arr def UpperCamelCase_ ( ): a_ = list(range(10 , 0 , -1 ) ) print("""Initial List""" ) print(*A__ ) a_ = odd_even_transposition(A__ ) print("""Sorted List\n""" ) print(*A__ ) if __name__ == "__main__": main()
263
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets lowercase__ =datasets.logging.get_logger(__name__) lowercase__ ='\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n booktitle = {Proceedings of the Fifth Conference on Machine Translation},\n month = {November},\n year = {2020},\n address = {Online},\n publisher = {Association for Computational Linguistics},\n pages = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n title = "{COMET}: A Neural Framework for {MT} Evaluation",\n author = "Rei, Ricardo and\n Stewart, Craig and\n Farinha, Ana C and\n Lavie, Alon",\n booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n month = nov,\n year = "2020",\n address = "Online",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n pages = "2685--2702",\n}\n' lowercase__ ='\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n' lowercase__ ='\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n `scores`: List of scores.\n\nExamples:\n\n >>> comet_metric = datasets.load_metric(\'comet\')\n >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use\n >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n >>> print([round(v, 2) for v in results["scores"]])\n [0.19, 0.92]\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase__ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://unbabel.github.io/COMET/html/index.html""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """sources""": datasets.Value("""string""" , id="""sequence""" ), """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/Unbabel/COMET"""] , reference_urls=[ """https://github.com/Unbabel/COMET""", """https://www.aclweb.org/anthology/2020.emnlp-main.213/""", """http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""", ] , ) def lowerCAmelCase__ ( self , UpperCAmelCase ): if self.config_name == "default": a_ = comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da""" ) ) else: a_ = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def lowerCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=False ): if gpus is None: a_ = 1 if torch.cuda.is_available() else 0 a_ = {"""src""": sources, """mt""": predictions, """ref""": references} a_ = [dict(zip(UpperCAmelCase , UpperCAmelCase ) ) for t in zip(*data.values() )] a_ , a_ = self.scorer.predict(UpperCAmelCase , gpus=UpperCAmelCase , progress_bar=UpperCAmelCase ) return {"mean_score": mean_score, "scores": scores}
263
1
"""simple docstring""" import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def UpperCamelCase ( _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[Any]=False ): __a = OmegaConf.load(_lowerCAmelCase ) if display: print(yaml.dump(OmegaConf.to_container(_lowerCAmelCase ) ) ) return config def UpperCamelCase ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Union[str, Any]=None , _lowerCAmelCase : List[str]=None ): if conf_path is None: __a = """./model_checkpoints/vqgan_only.yaml""" __a = load_config(_lowerCAmelCase , display=_lowerCAmelCase ) __a = VQModel(**config.model.params ) if ckpt_path is None: __a = """./model_checkpoints/vqgan_only.pt""" __a = torch.load(_lowerCAmelCase , map_location=_lowerCAmelCase ) if ".ckpt" in ckpt_path: __a = sd["""state_dict"""] model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) model.to(_lowerCAmelCase ) del sd return model def UpperCamelCase ( _lowerCAmelCase : Dict , _lowerCAmelCase : List[Any] ): __a , __a , __a = model.encode(_lowerCAmelCase ) print(f"""VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}""" ) __a = model.decode(_lowerCAmelCase ) return xrec def UpperCamelCase ( _lowerCAmelCase : Tuple , _lowerCAmelCase : Union[str, Any]=False ): __a , __a = string.rsplit(""".""" , 1 ) if reload: __a = importlib.import_module(_lowerCAmelCase ) importlib.reload(_lowerCAmelCase ) return getattr(importlib.import_module(_lowerCAmelCase , package=_lowerCAmelCase ) , cls ) def UpperCamelCase ( _lowerCAmelCase : Tuple ): if "target" not in config: raise KeyError("""Expected key `target` to instantiate.""" ) return get_obj_from_str(config["""target"""] )(**config.get("""params""" , {} ) ) def UpperCamelCase ( _lowerCAmelCase : int , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Tuple=True , _lowerCAmelCase : Optional[Any]=True ): __a = instantiate_from_config(_lowerCAmelCase ) if sd is not None: model.load_state_dict(_lowerCAmelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def UpperCamelCase ( _lowerCAmelCase : List[str] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Optional[int] ): # load the specified checkpoint if ckpt: __a = torch.load(_lowerCAmelCase , map_location="""cpu""" ) __a = pl_sd["""global_step"""] print(f"""loaded model from global step {global_step}.""" ) else: __a = {"""state_dict""": None} __a = None __a = load_model_from_config(config.model , pl_sd["""state_dict"""] , gpu=_lowerCAmelCase , eval_mode=_lowerCAmelCase )["""model"""] return model, global_step
173
"""simple docstring""" import math from datetime import datetime, timedelta def UpperCamelCase ( _lowerCAmelCase : int ): __a = year % 19 __a = year % 4 __a = year % 7 __a = math.floor(year / 100 ) __a = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __a = leap_day_inhibits / 4 __a = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __a = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __a = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __a = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(_lowerCAmelCase , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(_lowerCAmelCase , 4 , 18 ) else: return datetime(_lowerCAmelCase , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (19_94, 20_00, 20_10, 20_21, 20_23): __A = """will be""" if year > datetime.now().year else """was""" print(f'Easter in {year} {tense} {gauss_easter(year)}')
173
1
'''simple docstring''' from collections.abc import Callable def __UpperCAmelCase ( A : Callable[[float], float] , A : float , A : float ) -> float: UpperCAmelCase_ : float = a UpperCAmelCase_ : float = b if function(A ) == 0: # one of the a or b is a root for the function return a elif function(A ) == 0: return b elif ( function(A ) * function(A ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('''could not find root in given interval.''' ) else: UpperCAmelCase_ : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(A ) == 0: return mid elif function(A ) * function(A ) < 0: UpperCAmelCase_ : Dict = mid else: UpperCAmelCase_ : Any = mid UpperCAmelCase_ : int = start + (end - start) / 2.0 return mid def __UpperCAmelCase ( A : float ) -> float: return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_000)) import doctest doctest.testmod()
541
'''simple docstring''' import collections import os import re from pathlib import Path _UpperCamelCase : Optional[int] = 'src/transformers' # Matches is_xxx_available() _UpperCamelCase : int = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} _UpperCamelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _UpperCamelCase : List[str] = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available _UpperCamelCase : Any = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") _UpperCamelCase : Dict = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _UpperCamelCase : Tuple = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", _UpperCamelCase : Union[str, Any] = re.compile(R'^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], _UpperCamelCase : str = re.compile(R'^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo _UpperCamelCase : Union[str, Any] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: _UpperCamelCase : Optional[int] = re.compile(R'^\s*try:') # Catches a line with else: _UpperCamelCase : List[Any] = re.compile(R'^\s*else:') def __UpperCAmelCase ( A : Any ) -> Tuple: if _re_test_backend.search(A ) is None: return None UpperCAmelCase_ : str = [b[0] for b in _re_backend.findall(A )] backends.sort() return "_and_".join(A ) def __UpperCAmelCase ( A : List[Any] ) -> Optional[int]: with open(A , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: UpperCAmelCase_ : str = f.readlines() UpperCAmelCase_ : List[str] = 0 while line_index < len(A ) and not lines[line_index].startswith('''_import_structure = {''' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A ): return None # First grab the objects without a specific backend in _import_structure UpperCAmelCase_ : Tuple = [] while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None: UpperCAmelCase_ : List[Any] = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A ): UpperCAmelCase_ : str = _re_one_line_import_struct.search(A ).groups()[0] UpperCAmelCase_ : Any = re.findall(r'''\[([^\]]+)\]''' , A ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] ) line_index += 1 continue UpperCAmelCase_ : Dict = _re_import_struct_key_value.search(A ) if single_line_import_search is not None: UpperCAmelCase_ : List[str] = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(A ) > 0] objects.extend(A ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) line_index += 1 UpperCAmelCase_ : int = {'''none''': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('''if TYPE_CHECKING''' ): # If the line is an if not is_backend_available, we grab all objects associated. UpperCAmelCase_ : Any = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCAmelCase_ : int = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCAmelCase_ : str = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ): UpperCAmelCase_ : Optional[Any] = lines[line_index] if _re_import_struct_add_one.search(A ) is not None: objects.append(_re_import_struct_add_one.search(A ).groups()[0] ) elif _re_import_struct_add_many.search(A ) is not None: UpperCAmelCase_ : Dict = _re_import_struct_add_many.search(A ).groups()[0].split(''', ''' ) UpperCAmelCase_ : Dict = [obj[1:-1] for obj in imports if len(A ) > 0] objects.extend(A ) elif _re_between_brackets.search(A ) is not None: UpperCAmelCase_ : int = _re_between_brackets.search(A ).groups()[0].split(''', ''' ) UpperCAmelCase_ : List[Any] = [obj[1:-1] for obj in imports if len(A ) > 0] objects.extend(A ) elif _re_quote_object.search(A ) is not None: objects.append(_re_quote_object.search(A ).groups()[0] ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) elif line.startswith(''' ''' * 1_2 + '''"''' ): objects.append(line[1_3:-3] ) line_index += 1 UpperCAmelCase_ : int = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend UpperCAmelCase_ : Union[str, Any] = [] while ( line_index < len(A ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('''else''' ) ): UpperCAmelCase_ : int = lines[line_index] UpperCAmelCase_ : int = _re_import.search(A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 UpperCAmelCase_ : int = {'''none''': objects} # Let's continue with backend-specific objects while line_index < len(A ): # If the line is an if is_backend_available, we grab all objects associated. UpperCAmelCase_ : Optional[int] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCAmelCase_ : Optional[int] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCAmelCase_ : str = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ): UpperCAmelCase_ : Tuple = lines[line_index] UpperCAmelCase_ : Tuple = _re_import.search(A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 1_2 ): objects.append(line[1_2:-2] ) line_index += 1 UpperCAmelCase_ : Optional[Any] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def __UpperCAmelCase ( A : Dict , A : Union[str, Any] ) -> Optional[Any]: def find_duplicates(A : Optional[int] ): return [k for k, v in collections.Counter(A ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] UpperCAmelCase_ : str = [] for key in import_dict_objects.keys(): UpperCAmelCase_ : Union[str, Any] = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F"Duplicate _import_structure definitions for: {duplicate_imports}" ) UpperCAmelCase_ : Optional[int] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): UpperCAmelCase_ : Optional[int] = '''base imports''' if key == '''none''' else F"{key} backend" errors.append(F"Differences for {name}:" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F" {a} in TYPE_HINT but not in _import_structure." ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F" {a} in _import_structure but not in TYPE_HINT." ) return errors def __UpperCAmelCase ( ) -> Union[str, Any]: UpperCAmelCase_ : Tuple = [] for root, _, files in os.walk(A ): if "__init__.py" in files: UpperCAmelCase_ : List[Any] = os.path.join(A , '''__init__.py''' ) UpperCAmelCase_ : str = parse_init(A ) if objects is not None: UpperCAmelCase_ : List[str] = analyze_results(*A ) if len(A ) > 0: UpperCAmelCase_ : Optional[Any] = F"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append('''\n'''.join(A ) ) if len(A ) > 0: raise ValueError('''\n\n'''.join(A ) ) def __UpperCAmelCase ( ) -> str: UpperCAmelCase_ : Any = [] for path, directories, files in os.walk(A ): for folder in directories: # Ignore private modules if folder.startswith('''_''' ): directories.remove(A ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A ) / folder).glob('''*.py''' ) ) ) == 0: continue UpperCAmelCase_ : Union[str, Any] = str((Path(A ) / folder).relative_to(A ) ) UpperCAmelCase_ : List[Any] = short_path.replace(os.path.sep , '''.''' ) submodules.append(A ) for fname in files: if fname == "__init__.py": continue UpperCAmelCase_ : Optional[Any] = str((Path(A ) / fname).relative_to(A ) ) UpperCAmelCase_ : Union[str, Any] = short_path.replace('''.py''' , '''''' ).replace(os.path.sep , '''.''' ) if len(submodule.split('''.''' ) ) == 1: submodules.append(A ) return submodules _UpperCamelCase : List[Any] = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', 'models.esm.openfold_utils', ] def __UpperCAmelCase ( ) -> int: # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import UpperCAmelCase_ : Dict = direct_transformers_import(A ) UpperCAmelCase_ : List[str] = set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(A , '''__init__.py''' ) , '''r''' ) as f: UpperCAmelCase_ : Dict = f.read() import_structure_keys.update(set(re.findall(r'''import_structure\[\"([^\"]*)\"\]''' , A ) ) ) UpperCAmelCase_ : Union[str, Any] = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(A ) > 0: UpperCAmelCase_ : Optional[Any] = '''\n'''.join(F"- {module}" for module in module_not_registered ) raise ValueError( '''The following submodules are not properly registed in the main init of Transformers:\n''' F"{list_of_modules}\n" '''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' ) if __name__ == "__main__": check_all_inits() check_submodules()
541
1
'''simple docstring''' 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 = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class A__ ( _snake_case ): lowercase = "camembert" def __init__( self , UpperCamelCase__=30522 , UpperCamelCase__=768 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=2 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-1_2 , UpperCamelCase__=1 , UpperCamelCase__=0 , UpperCamelCase__=2 , UpperCamelCase__="absolute" , UpperCamelCase__=True , UpperCamelCase__=None , **UpperCamelCase__ , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) 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_ = type_vocab_size A_ = initializer_range A_ = layer_norm_eps A_ = position_embedding_type A_ = use_cache A_ = classifier_dropout class A__ ( _snake_case ): @property def snake_case_ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": A_ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: A_ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
716
'''simple docstring''' from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A__ ( _snake_case ): lowercase = "ClapFeatureExtractor" lowercase = ("RobertaTokenizer", "RobertaTokenizerFast") def __init__( self , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: '''simple docstring''' super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ ) -> Tuple: '''simple docstring''' A_ = kwargs.pop("""sampling_rate""" , UpperCamelCase__ ) if text is None and audios is None: raise ValueError("""You have to specify either text or audios. Both cannot be none.""" ) if text is not None: A_ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if audios is not None: A_ = self.feature_extractor( UpperCamelCase__ , sampling_rate=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) if text is not None and audios is not None: A_ = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCamelCase__ ) , tensor_type=UpperCamelCase__ ) def snake_case_ ( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> Optional[int]: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def snake_case_ ( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> str: '''simple docstring''' return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ ) @property def snake_case_ ( self ) -> int: '''simple docstring''' A_ = self.tokenizer.model_input_names A_ = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
667
0
"""simple docstring""" import math def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): return math.pow(lowerCAmelCase__ , 2 ) - a def a__ ( lowerCAmelCase__ ): return 2 * x def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = 2.0 while start <= a: UpperCAmelCase_ = math.pow(lowerCAmelCase__ , 2 ) return start def a__ ( lowerCAmelCase__ , lowerCAmelCase__ = 9999 , lowerCAmelCase__ = 0.00000000000001 ): if a < 0: raise ValueError("math domain error" ) UpperCAmelCase_ = get_initial_point(lowerCAmelCase__ ) for _ in range(lowerCAmelCase__ ): UpperCAmelCase_ = value UpperCAmelCase_ = value - fx(lowerCAmelCase__ , lowerCAmelCase__ ) / fx_derivative(lowerCAmelCase__ ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
82
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCamelCase : Tuple = { """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class _lowercase ( _A ): _a : Dict = 'pegasus' _a : Tuple = ['past_key_values'] _a : str = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , a=5_0_2_6_5 , a=1_0_2_4 , a=1_2 , a=4_0_9_6 , a=1_6 , a=1_2 , a=4_0_9_6 , a=1_6 , a=0.0 , a=0.0 , a=True , a=True , a="gelu" , a=1_0_2_4 , a=0.1 , a=0.0 , a=0.0 , a=0.02 , a=0 , a=False , a=0 , a=1 , a=1 , **a , ): snake_case__ : List[Any] =vocab_size snake_case__ : Optional[int] =max_position_embeddings snake_case__ : str =d_model snake_case__ : Tuple =encoder_ffn_dim snake_case__ : str =encoder_layers snake_case__ : Union[str, Any] =encoder_attention_heads snake_case__ : Tuple =decoder_ffn_dim snake_case__ : Optional[Any] =decoder_layers snake_case__ : Union[str, Any] =decoder_attention_heads snake_case__ : Optional[Any] =dropout snake_case__ : str =attention_dropout snake_case__ : Optional[int] =activation_dropout snake_case__ : Union[str, Any] =activation_function snake_case__ : List[Any] =init_std snake_case__ : Any =encoder_layerdrop snake_case__ : int =decoder_layerdrop snake_case__ : Any =use_cache snake_case__ : Tuple =encoder_layers snake_case__ : Optional[Any] =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=a , eos_token_id=a , is_encoder_decoder=a , decoder_start_token_id=a , forced_eos_token_id=a , **a , ) @property def lowercase__ ( self ): return self.encoder_attention_heads @property def lowercase__ ( self ): return self.d_model
385
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _a ( UpperCamelCase__ ): _lowercase : Optional[Any] = '''ClapFeatureExtractor''' _lowercase : Any = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self: Union[str, Any] , UpperCamelCase_: str , UpperCamelCase_: Tuple ) -> Tuple: """simple docstring""" super().__init__(UpperCamelCase_ , UpperCamelCase_ ) def __call__( self: Optional[int] , UpperCamelCase_: Optional[Any]=None , UpperCamelCase_: Any=None , UpperCamelCase_: Dict=None , **UpperCamelCase_: Union[str, Any] ) -> Optional[Any]: """simple docstring""" lowercase__ = kwargs.pop('''sampling_rate''' , UpperCamelCase_ ) if text is None and audios is None: raise ValueError('''You have to specify either text or audios. Both cannot be none.''' ) if text is not None: lowercase__ = self.tokenizer(UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ ) if audios is not None: lowercase__ = self.feature_extractor( UpperCamelCase_ , sampling_rate=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ ) if text is not None and audios is not None: lowercase__ = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCamelCase_ ) , tensor_type=UpperCamelCase_ ) def lowerCamelCase_ ( self: Tuple , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Optional[Any] ) -> Tuple: """simple docstring""" return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCamelCase_ ( self: Optional[int] , *UpperCamelCase_: Dict , **UpperCamelCase_: Tuple ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @property def lowerCamelCase_ ( self: str ) -> Optional[Any]: """simple docstring""" lowercase__ = self.tokenizer.model_input_names lowercase__ = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
429
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase = get_tests_dir('fixtures/test_sentencepiece.model') if is_sentencepiece_available(): import sentencepiece as sp lowerCAmelCase = 5 lowerCAmelCase = 10 @require_sentencepiece @require_tokenizers class _a ( UpperCamelCase__ , unittest.TestCase ): _lowercase : List[str] = SpeechaTextTokenizer _lowercase : List[str] = False _lowercase : Optional[Any] = True def lowerCamelCase_ ( self: Optional[Any] ) -> Any: """simple docstring""" super().setUp() lowercase__ = sp.SentencePieceProcessor() spm_model.Load(UpperCamelCase_ ) lowercase__ = ['''<s>''', '''<pad>''', '''</s>''', '''<unk>'''] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(UpperCamelCase_ ) )] lowercase__ = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) lowercase__ = Path(self.tmpdirname ) save_json(UpperCamelCase_ , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCamelCase_ , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) lowercase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self: List[str] ) -> Optional[int]: """simple docstring""" lowercase__ = '''<pad>''' lowercase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase_ ) , UpperCamelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase_ ) , UpperCamelCase_ ) def lowerCamelCase_ ( self: Any ) -> str: """simple docstring""" lowercase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(UpperCamelCase_ ) , 1_001 ) def lowerCamelCase_ ( self: List[Any] ) -> str: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_001 ) def lowerCamelCase_ ( self: Dict ) -> Optional[int]: """simple docstring""" lowercase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) lowercase__ = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCamelCase_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , [289, 50, 14, 174, 386] , ) lowercase__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( UpperCamelCase_ , [SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.'''] , ) lowercase__ = tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) lowercase__ = tokenizer.convert_ids_to_tokens(UpperCamelCase_ ) self.assertListEqual( UpperCamelCase_ , [SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.'''] , ) @slow def lowerCamelCase_ ( self: int ) -> Dict: """simple docstring""" lowercase__ = {'''input_ids''': [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_575, 2_666, 684, 1_582, 1_176, 12, 627, 149, 619, 20, 4_902, 563, 11, 20, 149, 261, 3_420, 2_356, 174, 142, 4_714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase_ , model_name='''facebook/s2t-small-mustc-en-de-st''' , revision='''a14f04cf0776c02f62a8cb800cf7909e15ea23ad''' , ) @require_sentencepiece class _a ( unittest.TestCase ): _lowercase : Union[str, Any] = '''valhalla/s2t_mustc_multilinguial_medium''' _lowercase : int = '''C\'est trop cool''' _lowercase : Any = '''Esto es genial''' @classmethod def lowerCamelCase_ ( cls: str ) -> Optional[int]: """simple docstring""" lowercase__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def lowerCamelCase_ ( self: int ) -> Optional[Any]: """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id['''pt'''] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id['''ru'''] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id['''it'''] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id['''de'''] , 11 ) def lowerCamelCase_ ( self: Union[str, Any] ) -> Any: """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 10_000 ) def lowerCamelCase_ ( self: Union[str, Any] ) -> str: """simple docstring""" self.assertIn(UpperCamelCase_ , self.tokenizer.all_special_ids ) lowercase__ = [ES_CODE, 4, 1_601, 47, 7_647, 2] lowercase__ = self.tokenizer.decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) lowercase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertNotIn(self.tokenizer.eos_token , UpperCamelCase_ ) def lowerCamelCase_ ( self: int ) -> List[Any]: """simple docstring""" lowercase__ = '''fr''' lowercase__ = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , UpperCamelCase_ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def lowerCamelCase_ ( self: Dict ) -> List[Any]: """simple docstring""" lowercase__ = '''fr''' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) lowercase__ = '''es''' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
429
1
from typing import TYPE_CHECKING from ..utils import _LazyModule UpperCamelCase__ : int = { """config""": [ """EXTERNAL_DATA_FORMAT_SIZE_LIMIT""", """OnnxConfig""", """OnnxConfigWithPast""", """OnnxSeq2SeqConfigWithPast""", """PatchingSpec""", ], """convert""": ["""export""", """validate_model_outputs"""], """features""": ["""FeaturesManager"""], """utils""": ["""ParameterFormat""", """compute_serialized_parameters_size"""], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys UpperCamelCase__ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
387
import argparse import copy def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[Any]: """simple docstring""" a = {} with open(snake_case_ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: a = [] _list.append([line.split()[1], line.split()[2]] ) a = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: a = [] _list.append([line.split()[0], line.split()[2]] ) a = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str: """simple docstring""" with open(snake_case_ ) as f: a = f.read(1 ) a = start_node a = [] a = start_node a = 0 while visiting not in first_solution: a = 1_0_0_0_0 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(snake_case_ ) and k[0] not in first_solution: a = k[1] a = k[0] first_solution.append(snake_case_ ) a = distance_of_first_solution + int(snake_case_ ) a = best_node first_solution.append(snake_case_ ) a = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 a = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0_0_0_0 ) return first_solution, distance_of_first_solution def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = [] for n in solution[1:-1]: a = solution.index(snake_case_ ) for kn in solution[1:-1]: a = solution.index(snake_case_ ) if n == kn: continue a = copy.deepcopy(snake_case_ ) a = kn a = n a = 0 for k in _tmp[:-1]: a = _tmp[_tmp.index(snake_case_ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: a = distance + int(i[1] ) _tmp.append(snake_case_ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) a = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda snake_case_ : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" a = 1 a = first_solution a = [] a = distance_of_first_solution a = solution while count <= iters: a = find_neighborhood(snake_case_, snake_case_ ) a = 0 a = neighborhood[index_of_best_solution] a = len(snake_case_ ) - 1 a = False while not found: a = 0 while i < len(snake_case_ ): if best_solution[i] != solution[i]: a = best_solution[i] a = solution[i] break a = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) a = True a = best_solution[:-1] a = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: a = cost a = solution else: a = index_of_best_solution + 1 a = neighborhood[index_of_best_solution] if len(snake_case_ ) >= size: tabu_list.pop(0 ) a = count + 1 return best_solution_ever, best_cost def SCREAMING_SNAKE_CASE__ ( snake_case_=None ) -> List[str]: """simple docstring""" a = generate_neighbours(args.File ) a , a = generate_first_solution( args.File, snake_case_ ) a , a = tabu_search( snake_case_, snake_case_, snake_case_, args.Iterations, args.Size, ) print(f"""Best solution: {best_sol}, with total distance: {best_cost}.""" ) if __name__ == "__main__": UpperCamelCase__ : int = argparse.ArgumentParser(description="""Tabu Search""") parser.add_argument( """-f""", """--File""", type=str, help="""Path to the file containing the data""", required=True, ) parser.add_argument( """-i""", """--Iterations""", type=int, help="""How many iterations the algorithm should perform""", required=True, ) parser.add_argument( """-s""", """--Size""", type=int, help="""Size of the tabu list""", required=True ) # Pass the arguments to main method main(parser.parse_args())
387
1
'''simple docstring''' from __future__ import annotations from math import pi def __A ( _lowercase , _lowercase , _lowercase ): '''simple docstring''' if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if inductance < 0: raise ValueError('''Inductance cannot be negative''' ) if frequency < 0: raise ValueError('''Frequency cannot be negative''' ) if reactance < 0: raise ValueError('''Inductive reactance cannot be negative''' ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
715
import math def __A ( _lowercase ): '''simple docstring''' _A = [] _A = 2 _A = int(math.sqrt(_lowercase ) ) # Size of every segment _A = [True] * (end + 1) _A = [] while start <= end: if temp[start] is True: in_prime.append(_lowercase ) for i in range(start * start , end + 1 , _lowercase ): _A = False start += 1 prime += in_prime _A = end + 1 _A = min(2 * end , _lowercase ) while low <= n: _A = [True] * (high - low + 1) for each in in_prime: _A = math.floor(low / each ) * each if t < low: t += each for j in range(_lowercase , high + 1 , _lowercase ): _A = False for j in range(len(_lowercase ) ): if temp[j] is True: prime.append(j + low ) _A = high + 1 _A = min(high + end , _lowercase ) return prime print(sieve(10**6))
62
0
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all BART models at https://huggingface.co/models?filter=bart _UpperCAmelCase : Optional[int] = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, } _UpperCAmelCase : Union[str, Any] = { '''facebook/bart-base''': 10_24, '''facebook/bart-large''': 10_24, '''facebook/bart-large-mnli''': 10_24, '''facebook/bart-large-cnn''': 10_24, '''facebook/bart-large-xsum''': 10_24, '''yjernite/bart_eli5''': 10_24, } @lru_cache() def UpperCamelCase ( ) -> int: '''simple docstring''' lowercase =( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) lowercase =bs[:] lowercase =0 for b in range(2**8 ): if b not in bs: bs.append(lowercase_ ) cs.append(2**8 + n ) n += 1 lowercase =[chr(lowercase_ ) for n in cs] return dict(zip(lowercase_ , lowercase_ ) ) def UpperCamelCase ( lowercase_ : int ) -> Optional[int]: '''simple docstring''' lowercase =set() lowercase =word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowercase =char return pairs class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = ['input_ids', 'attention_mask'] def __init__( self , snake_case_ , snake_case_ , snake_case_="replace" , snake_case_="<s>" , snake_case_="</s>" , snake_case_="</s>" , snake_case_="<s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_="<mask>" , snake_case_=False , **snake_case_ , ): lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else bos_token lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else eos_token lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else sep_token lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else cls_token lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else unk_token lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else mask_token super().__init__( errors=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , cls_token=snake_case_ , pad_token=snake_case_ , mask_token=snake_case_ , add_prefix_space=snake_case_ , **snake_case_ , ) with open(snake_case_ , encoding='''utf-8''' ) as vocab_handle: lowercase =json.load(snake_case_ ) lowercase ={v: k for k, v in self.encoder.items()} lowercase =errors # how to handle errors in decoding lowercase =bytes_to_unicode() lowercase ={v: k for k, v in self.byte_encoder.items()} with open(snake_case_ , encoding='''utf-8''' ) as merges_handle: lowercase =merges_handle.read().split('''\n''' )[1:-1] lowercase =[tuple(merge.split() ) for merge in bpe_merges] lowercase =dict(zip(snake_case_ , range(len(snake_case_ ) ) ) ) lowercase ={} lowercase =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowercase =re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def _A( self ): return len(self.encoder ) def _A( self ): return dict(self.encoder , **self.added_tokens_encoder ) def _A( self , snake_case_ ): if token in self.cache: return self.cache[token] lowercase =tuple(snake_case_ ) lowercase =get_pairs(snake_case_ ) if not pairs: return token while True: lowercase =min(snake_case_ , key=lambda snake_case_ : self.bpe_ranks.get(snake_case_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowercase , lowercase =bigram lowercase =[] lowercase =0 while i < len(snake_case_ ): try: lowercase =word.index(snake_case_ , snake_case_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowercase =j if word[i] == first and i < len(snake_case_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowercase =tuple(snake_case_ ) lowercase =new_word if len(snake_case_ ) == 1: break else: lowercase =get_pairs(snake_case_ ) lowercase =''' '''.join(snake_case_ ) lowercase =word return word def _A( self , snake_case_ ): lowercase =[] for token in re.findall(self.pat , snake_case_ ): lowercase =''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(snake_case_ ).split(''' ''' ) ) return bpe_tokens def _A( self , snake_case_ ): return self.encoder.get(snake_case_ , self.encoder.get(self.unk_token ) ) def _A( self , snake_case_ ): return self.decoder.get(snake_case_ ) def _A( self , snake_case_ ): lowercase =''''''.join(snake_case_ ) lowercase =bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def _A( self , snake_case_ , snake_case_ = None ): if not os.path.isdir(snake_case_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowercase =os.path.join( snake_case_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase =os.path.join( snake_case_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case_ , ensure_ascii=snake_case_ ) + '''\n''' ) lowercase =0 with open(snake_case_ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda snake_case_ : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''' ) lowercase =token_index writer.write(''' '''.join(snake_case_ ) + '''\n''' ) index += 1 return vocab_file, merge_file def _A( self , snake_case_ , snake_case_ = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowercase =[self.cls_token_id] lowercase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _A( self , snake_case_ , snake_case_ = None , snake_case_ = 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, 1] + ([0] * len(snake_case_ )) + [1] def _A( self , snake_case_ , snake_case_ = None ): lowercase =[self.sep_token_id] lowercase =[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 _A( self , snake_case_ , snake_case_=False , **snake_case_ ): lowercase =kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(snake_case_ ) > 0 and not text[0].isspace()): lowercase =''' ''' + text return (text, kwargs)
72
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __A : Optional[Any] = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' lowerCamelCase__ = field(default=__snake_case , metadata={"help": "Whether to use SortishSampler or not."} ) lowerCamelCase__ = field( default=__snake_case , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowerCamelCase__ = field( default=__snake_case , metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } , ) lowerCamelCase__ = field( default=__snake_case , metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } , ) lowerCamelCase__ = field( default=__snake_case , metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } , ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE = super().to_dict() for k, v in d.items(): if isinstance(__lowerCamelCase , __lowerCamelCase ): SCREAMING_SNAKE_CASE = v.to_dict() return d
16
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py lowerCamelCase = '''src/diffusers''' lowerCamelCase = '''.''' # This is to make sure the diffusers module imported is the one in the repo. lowerCamelCase = importlib.util.spec_from_file_location( """diffusers""", os.path.join(DIFFUSERS_PATH, """__init__.py"""), submodule_search_locations=[DIFFUSERS_PATH], ) lowerCamelCase = spec.loader.load_module() def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase ) -> List[Any]: return line.startswith(_UpperCAmelCase ) or len(_UpperCAmelCase ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$" , _UpperCAmelCase ) is not None def SCREAMING_SNAKE_CASE( __UpperCamelCase ) -> str: a__ : Optional[Any] = object_name.split("." ) a__ : List[Any] = 0 # First let's find the module where our object lives. a__ : Optional[Any] = parts[i] while i < len(_UpperCAmelCase ) and not os.path.isfile(os.path.join(_UpperCAmelCase , F'{module}.py' ) ): i += 1 if i < len(_UpperCAmelCase ): a__ : List[str] = os.path.join(_UpperCAmelCase , parts[i] ) if i >= len(_UpperCAmelCase ): raise ValueError(F'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(_UpperCAmelCase , F'{module}.py' ) , "r" , encoding="utf-8" , newline="\n" ) as f: a__ : Union[str, Any] = f.readlines() # Now let's find the class / func in the code! a__ : Tuple = "" a__ : int = 0 for name in parts[i + 1 :]: while ( line_index < len(_UpperCAmelCase ) and re.search(RF'^{indent}(class|def)\s+{name}(\(|\:)' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(_UpperCAmelCase ): raise ValueError(F' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). a__ : str = line_index while line_index < len(_UpperCAmelCase ) and _should_continue(lines[line_index] , _UpperCAmelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 a__ : int = lines[start_index:line_index] return "".join(_UpperCAmelCase ) lowerCamelCase = re.compile(R"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""") lowerCamelCase = re.compile(R"""^\s*(\S+)->(\S+)(\s+.*|$)""") lowerCamelCase = re.compile(R"""<FILL\s+[^>]*>""") def SCREAMING_SNAKE_CASE( __UpperCamelCase ) -> Tuple: a__ : List[str] = code.split("\n" ) a__ : Any = 0 while idx < len(_UpperCAmelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(_UpperCAmelCase ): return re.search(R"^(\s*)\S" , lines[idx] ).groups()[0] return "" def SCREAMING_SNAKE_CASE( __UpperCamelCase ) -> int: a__ : Any = len(get_indent(_UpperCAmelCase ) ) > 0 if has_indent: a__ : Optional[Any] = F'class Bla:\n{code}' a__ : Optional[int] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 , preview=_UpperCAmelCase ) a__ : Optional[int] = black.format_str(_UpperCAmelCase , mode=_UpperCAmelCase ) a__ , a__ : str = style_docstrings_in_code(_UpperCAmelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase=False ) -> str: with open(_UpperCAmelCase , "r" , encoding="utf-8" , newline="\n" ) as f: a__ : Dict = f.readlines() a__ : Dict = [] a__ : int = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(_UpperCAmelCase ): a__ : str = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. a__ , a__ , a__ : Any = search.groups() a__ : List[Any] = find_code_in_diffusers(_UpperCAmelCase ) a__ : Any = get_indent(_UpperCAmelCase ) a__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 a__ : List[Any] = theoretical_indent a__ : Tuple = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. a__ : List[Any] = True while line_index < len(_UpperCAmelCase ) and should_continue: line_index += 1 if line_index >= len(_UpperCAmelCase ): break a__ : Optional[Any] = lines[line_index] a__ : Optional[int] = _should_continue(_UpperCAmelCase , _UpperCAmelCase ) and re.search(F'^{indent}# End copy' , _UpperCAmelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 a__ : Dict = lines[start_index:line_index] a__ : Optional[Any] = "".join(_UpperCAmelCase ) # Remove any nested `Copied from` comments to avoid circular copies a__ : int = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(_UpperCAmelCase ) is None] a__ : Union[str, Any] = "\n".join(_UpperCAmelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(_UpperCAmelCase ) > 0: a__ : List[Any] = replace_pattern.replace("with" , "" ).split("," ) a__ : Union[str, Any] = [_re_replace_pattern.search(_UpperCAmelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue a__ , a__ , a__ : List[str] = pattern.groups() a__ : List[str] = re.sub(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if option.strip() == "all-casing": a__ : Optional[int] = re.sub(obja.lower() , obja.lower() , _UpperCAmelCase ) a__ : Any = re.sub(obja.upper() , obja.upper() , _UpperCAmelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line a__ : List[str] = blackify(lines[start_index - 1] + theoretical_code ) a__ : Optional[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: a__ : Optional[int] = lines[:start_index] + [theoretical_code] + lines[line_index:] a__ : Tuple = start_index + 1 if overwrite and len(_UpperCAmelCase ) > 0: # Warn the user a file has been modified. print(F'Detected changes, rewriting {filename}.' ) with open(_UpperCAmelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCAmelCase ) return diffs def SCREAMING_SNAKE_CASE( __UpperCamelCase = False ) -> str: a__ : Optional[int] = glob.glob(os.path.join(_UpperCAmelCase , "**/*.py" ) , recursive=_UpperCAmelCase ) a__ : Any = [] for filename in all_files: a__ : Any = is_copy_consistent(_UpperCAmelCase , _UpperCAmelCase ) diffs += [F'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(_UpperCAmelCase ) > 0: a__ : List[Any] = "\n".join(_UpperCAmelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") lowerCamelCase = parser.parse_args() check_copies(args.fix_and_overwrite)
716
import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""): lowerCamelCase = True from torch.cuda.amp import autocast lowerCamelCase = logging.getLogger(__name__) @dataclass class _a : '''simple docstring''' A :str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) A :Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) A :Optional[bool] = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) A :Optional[bool] = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "Whether to log verbose messages or not."} , ) A :Optional[float] = field( default=2.0 , metadata={"help": "Maximum temperature for gumbel softmax."} ) A :Optional[float] = field( default=0.5 , metadata={"help": "Minimum temperature for gumbel softmax."} ) A :Optional[float] = field( default=0.99_9995 , metadata={"help": "Decay of gumbel temperature during training."} ) def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase ) -> Any: logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) a__ : int = logging.WARNING if model_args.verbose_logging: a__ : List[Any] = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): a__ : Union[str, Any] = logging.INFO logger.setLevel(__UpperCamelCase ) @dataclass class _a : '''simple docstring''' A :str = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) A :Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) A :Optional[str] = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) A :Optional[str] = field( default="validation" , metadata={ "help": ( "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) A :Optional[str] = field( default="file" , metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"} , ) A :bool = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) A :Optional[int] = field( default=1 , metadata={ "help": "The percentage of the train set used as validation set in case there's no validation split" } , ) A :Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={"help": "The number of processes to use for the preprocessing."} , ) A :Optional[float] = field( default=20.0 , metadata={"help": "Filter audio files that are longer than `max_duration_in_seconds` seconds"} ) @dataclass class _a : '''simple docstring''' A :WavaVecaForPreTraining A :WavaVecaFeatureExtractor A :Union[bool, str] = "longest" A :Optional[int] = None A :Optional[int] = None def __call__( self , __UpperCAmelCase ): """simple docstring""" a__ : Dict = self.feature_extractor.pad( __UpperCAmelCase , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) a__ : Optional[int] = self.model._get_feat_extract_output_lengths(batch["input_values"].shape[-1] ) a__ : Optional[int] = batch["input_values"].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula a__ : Any = self.model._get_feat_extract_output_lengths(batch["attention_mask"].sum(-1 ) ).to( torch.long ) a__ : List[str] = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch["input_values"].device ) # these two operations makes sure that all values # before the output lengths indices are attended to a__ : List[Any] = 1 a__ : Optional[int] = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices a__ : Union[str, Any] = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=__UpperCAmelCase , min_masks=2 , ) return batch class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *__UpperCAmelCase , __UpperCAmelCase=1 , __UpperCAmelCase=0 , __UpperCAmelCase=1.0 , **__UpperCAmelCase ): """simple docstring""" super().__init__(*__UpperCAmelCase , **__UpperCAmelCase ) a__ : Optional[Any] = 0 a__ : Tuple = max_gumbel_temp a__ : str = min_gumbel_temp a__ : List[Any] = gumbel_temp_decay def _A ( self , __UpperCAmelCase , __UpperCAmelCase ): """simple docstring""" model.train() a__ : Optional[Any] = self._prepare_inputs(__UpperCAmelCase ) if self.use_amp: with autocast(): a__ : List[Any] = self.compute_loss(__UpperCAmelCase , __UpperCAmelCase ) else: a__ : List[Any] = self.compute_loss(__UpperCAmelCase , __UpperCAmelCase ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": a__ : str = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": a__ : List[Any] = loss.sum() / (inputs["mask_time_indices"]).sum() else: raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' ) if self.args.gradient_accumulation_steps > 1: a__ : Optional[Any] = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__UpperCAmelCase ).backward() elif self.use_apex: with amp.scale_loss(__UpperCAmelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__UpperCAmelCase ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def SCREAMING_SNAKE_CASE( ) -> int: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. a__ : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) a__ , a__ , a__ : str = parser.parse_args_into_dataclasses() configure_logger(__UpperCamelCase , __UpperCamelCase ) # Downloading and loading a dataset from the hub. a__ : List[str] = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" a__ : Tuple = DatasetDict() a__ : Tuple = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'{data_args.train_split_name}[:{data_args.validation_split_percentage}%]' , cache_dir=model_args.cache_dir , ) a__ : Optional[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'{data_args.train_split_name}[{data_args.validation_split_percentage}%:]' , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" a__ : List[Any] = DatasetDict() a__ : Optional[int] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split="validation" , cache_dir=model_args.cache_dir , ) a__ : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'{data_args.train_split_name}' , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported a__ : List[Any] = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=__UpperCamelCase ) def prepare_dataset(__UpperCamelCase ): # check that all files have the correct sampling rate a__ , a__ : List[str] = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays a__ : Optional[Any] = datasets.map( __UpperCamelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets["train"].column_names ) # filter audio files that are too long a__ : Tuple = vectorized_datasets.filter( lambda __UpperCamelCase : len(data["speech"] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(__UpperCamelCase ): return feature_extractor(batch["speech"] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` a__ : Tuple = vectorized_datasets.map( __UpperCamelCase , batched=__UpperCamelCase , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets["train"].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 a__ : List[Any] = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( "PreTraining is only supported for ``config.do_stable_layer_norm=True`` and" " ``config.feat_extract_norm='layer'" ) a__ : Optional[Any] = WavaVecaForPreTraining(__UpperCamelCase ) a__ : Dict = DataCollatorForWavaVecaPretraining(model=__UpperCamelCase , feature_extractor=__UpperCamelCase ) a__ : Optional[int] = WavaVecaPreTrainer( model=__UpperCamelCase , data_collator=__UpperCamelCase , args=__UpperCamelCase , train_dataset=vectorized_datasets["train"] , eval_dataset=vectorized_datasets["validation"] , tokenizer=__UpperCamelCase , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
207
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase: int ) -> int: '''simple docstring''' if not isinstance(_lowerCamelCase, _lowerCamelCase ): raise ValueError('''multiplicative_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''multiplicative_persistence() does not accept negative values''' ) lowerCAmelCase = 0 lowerCAmelCase = str(_lowerCamelCase ) while len(_lowerCamelCase ) != 1: lowerCAmelCase = [int(_lowerCamelCase ) for i in num_string] lowerCAmelCase = 1 for i in range(0, len(_lowerCamelCase ) ): total *= numbers[i] lowerCAmelCase = str(_lowerCamelCase ) steps += 1 return steps def __magic_name__ ( _lowerCamelCase: int ) -> int: '''simple docstring''' if not isinstance(_lowerCamelCase, _lowerCamelCase ): raise ValueError('''additive_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''additive_persistence() does not accept negative values''' ) lowerCAmelCase = 0 lowerCAmelCase = str(_lowerCamelCase ) while len(_lowerCamelCase ) != 1: lowerCAmelCase = [int(_lowerCamelCase ) for i in num_string] lowerCAmelCase = 0 for i in range(0, len(_lowerCamelCase ) ): total += numbers[i] lowerCAmelCase = str(_lowerCamelCase ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
535
"""simple docstring""" import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def __magic_name__ ( _lowerCamelCase: Optional[Any] ) -> Dict: '''simple docstring''' def wrapper(*_lowerCamelCase: Any, **_lowerCamelCase: Union[str, Any] ): lowerCAmelCase = timeit.default_timer() lowerCAmelCase = func(*_lowerCamelCase, **_lowerCamelCase ) lowerCAmelCase = timeit.default_timer() - starttime return delta lowerCAmelCase = func.__name__ return wrapper def __magic_name__ ( _lowerCamelCase: dict, _lowerCamelCase: List[Any]=100, _lowerCamelCase: int=None ) -> List[Any]: '''simple docstring''' lowerCAmelCase = [] lowerCAmelCase = seq_shapes or {} for i in range(_lowerCamelCase ): lowerCAmelCase = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(_lowerCamelCase, _ArrayXD ): lowerCAmelCase = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(_lowerCamelCase, datasets.Value ): if v.dtype == "string": lowerCAmelCase = '''The small grey turtle was surprisingly fast when challenged.''' else: lowerCAmelCase = np.random.randint(10, size=1 ).astype(v.dtype ).item() elif isinstance(_lowerCamelCase, datasets.Sequence ): while isinstance(_lowerCamelCase, datasets.Sequence ): lowerCAmelCase = v.feature lowerCAmelCase = seq_shapes[k] lowerCAmelCase = np.random.rand(*_lowerCamelCase ).astype(v.dtype ) lowerCAmelCase = data dummy_data.append((i, example) ) return dummy_data def __magic_name__ ( _lowerCamelCase: Tuple, _lowerCamelCase: Tuple, _lowerCamelCase: Union[str, Any]=100, _lowerCamelCase: List[Any]=None ) -> List[Any]: '''simple docstring''' lowerCAmelCase = generate_examples(_lowerCamelCase, num_examples=_lowerCamelCase, seq_shapes=_lowerCamelCase ) with ArrowWriter(features=_lowerCamelCase, path=_lowerCamelCase ) as writer: for key, record in dummy_data: lowerCAmelCase = features.encode_example(_lowerCamelCase ) writer.write(_lowerCamelCase ) lowerCAmelCase , lowerCAmelCase = writer.finalize() if not num_final_examples == num_examples: raise ValueError( F"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.""" ) lowerCAmelCase = datasets.Dataset.from_file(filename=_lowerCamelCase, info=datasets.DatasetInfo(features=_lowerCamelCase ) ) return dataset
535
1
# Copyright 2021 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. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu __lowerCamelCase : str = [ '''EAGER''', '''AOT_EAGER''', '''INDUCTOR''', '''NVFUSER''', '''AOT_NVFUSER''', '''AOT_CUDAGRAPHS''', '''OFI''', '''FX2TRT''', '''ONNXRT''', '''IPEX''', ] def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Tuple , __UpperCamelCase : Union[str, Any]=None , __UpperCamelCase : List[Any]=None , __UpperCamelCase : Optional[Any]=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = True while ask_again: SCREAMING_SNAKE_CASE__ = input(__UpperCamelCase ) try: if default is not None and len(__UpperCamelCase ) == 0: return default return convert_value(__UpperCamelCase ) if convert_value is not None else result except Exception: if error_message is not None: print(__UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str , __UpperCamelCase : Any=[] , __UpperCamelCase : Any=None , __UpperCamelCase : List[str]=0 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BulletMenu(__UpperCamelCase , __UpperCamelCase ) SCREAMING_SNAKE_CASE__ = menu.run(default_choice=__UpperCamelCase ) return convert_value(__UpperCamelCase ) if convert_value is not None else result def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = int(__UpperCamelCase ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = int(__UpperCamelCase ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = int(__UpperCamelCase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = int(__UpperCamelCase ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = int(__UpperCamelCase ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any ) -> int: """simple docstring""" return {"yes": True, "no": False}[value.lower()] class __snake_case ( argparse.RawDescriptionHelpFormatter ): def __a ( self : str , _lowercase : List[Any] , _lowercase : List[str] , _lowercase : Tuple , _lowercase : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = super()._format_usage(_lowercase , _lowercase , _lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ = usage.replace("""<command> [<args>] """ , """""" ) return usage
710
import os __lowerCamelCase : Union[str, Any] = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 while index < len(__UpperCamelCase ) - 1: SCREAMING_SNAKE_CASE__ = SYMBOLS[numerals[index]] SCREAMING_SNAKE_CASE__ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = """""" SCREAMING_SNAKE_CASE__ = num // 10_00 numerals += m_count * "M" num %= 10_00 SCREAMING_SNAKE_CASE__ = num // 1_00 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_00 SCREAMING_SNAKE_CASE__ = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str = "/p089_roman.txt" ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 with open(os.path.dirname(__UpperCamelCase ) + roman_numerals_filename ) as filea: SCREAMING_SNAKE_CASE__ = filea.readlines() for line in lines: SCREAMING_SNAKE_CASE__ = line.strip() SCREAMING_SNAKE_CASE__ = parse_roman_numerals(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ = generate_roman_numerals(__UpperCamelCase ) savings += len(__UpperCamelCase ) - len(__UpperCamelCase ) return savings if __name__ == "__main__": print(F"""{solution() = }""")
379
0
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class a_ ( unittest.TestCase ): def __init__( self : Optional[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" snake_case : Dict = parent def lowerCAmelCase( self : List[Any] ): """simple docstring""" return {} def a_ ( ) -> Dict: """simple docstring""" snake_case : List[Any] = '''<HTML> <HEAD> <TITLE>sample document</TITLE> </HEAD> <BODY BGCOLOR="FFFFFF"> <HR> <a href="http://google.com">Goog</a> <H1>This is one header</H1> <H2>This is a another Header</H2> <P>Travel from <P> <B>SFO to JFK</B> <BR> <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B> <HR> <div style="color:#0000FF"> <h3>Traveler <b> name </b> is <p> John Doe </p> </div>''' snake_case : Tuple = ''' <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> ''' return [html_string_a, html_string_a] @require_bsa class a_ ( a , unittest.TestCase ): A__ : Union[str, Any] = MarkupLMFeatureExtractor if is_bsa_available() else None def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Tuple = MarkupLMFeatureExtractionTester(self ) @property def lowerCAmelCase( self : List[str] ): """simple docstring""" return self.feature_extract_tester.prepare_feat_extract_dict() def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Tuple = self.feature_extraction_class() # Test not batched input snake_case : str = get_html_strings()[0] snake_case : Union[str, Any] = feature_extractor(_snake_case ) # fmt: off snake_case : int = [['''sample document''', '''Goog''', '''This is one header''', '''This is a another Header''', '''Travel from''', '''SFO to JFK''', '''on May 2, 2015 at 2:00 pm. For details go to confirm.com''', '''Traveler''', '''name''', '''is''', '''John Doe''']] snake_case : List[Any] = [['''/html/head/title''', '''/html/body/a''', '''/html/body/h1''', '''/html/body/h2''', '''/html/body/p''', '''/html/body/p/p/b[1]''', '''/html/body/p/p/b[2]/i''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/b''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/p''']] # fmt: on self.assertEqual(encoding.nodes , _snake_case ) self.assertEqual(encoding.xpaths , _snake_case ) # Test batched snake_case : Dict = get_html_strings() snake_case : int = feature_extractor(_snake_case ) # fmt: off snake_case : Optional[Any] = expected_nodes + [['''My First Heading''', '''My first paragraph.''']] snake_case : Any = expected_xpaths + [['''/html/body/h1''', '''/html/body/p''']] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , _snake_case ) self.assertEqual(encoding.xpaths , _snake_case )
598
import os import pytest from transformers.dynamic_module_utils import get_imports A : List[str] = '\nimport os\n' A : int = '\ndef foo():\n import os\n return False\n' A : List[Any] = '\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n' A : int = '\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n' A : Dict = '\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n' A : Optional[Any] = '\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n' A : List[Any] = '\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n' A : Optional[Any] = '\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n' A : int = '\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n' A : Any = '\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n' A : Union[str, Any] = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('''case''' , a__ ) def __lowerCAmelCase ( a__ , a__ ) -> Optional[Any]: __a = os.path.join(a__ , '''test_file.py''' ) with open(a__ , '''w''' ) as _tmp_file: _tmp_file.write(a__ ) __a = get_imports(a__ ) assert parsed_imports == ["os"]
219
0
import os a_ : Union[str, Any] = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 1_00, 'D': 5_00, 'M': 10_00} def __a ( __UpperCAmelCase ): a__ = 0 a__ = 0 while index < len(__UpperCAmelCase ) - 1: a__ = SYMBOLS[numerals[index]] a__ = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def __a ( __UpperCAmelCase ): a__ = '''''' a__ = num // 1000 numerals += m_count * "M" num %= 1000 a__ = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 a__ = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def __a ( __UpperCAmelCase = "/p089_roman.txt" ): a__ = 0 with open(os.path.dirname(__UpperCAmelCase ) + roman_numerals_filename ) as filea: a__ = filea.readlines() for line in lines: a__ = line.strip() a__ = parse_roman_numerals(__UpperCAmelCase ) a__ = generate_roman_numerals(__UpperCAmelCase ) savings += len(__UpperCAmelCase ) - len(__UpperCAmelCase ) return savings if __name__ == "__main__": print(f'{solution() = }')
148
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers a_ : str = '3' print('Python version:', sys.version) print('transformers version:', transformers.__version__) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) print('Cuda version:', torch.version.cuda) print('CuDNN version:', torch.backends.cudnn.version()) print('Number of GPUs available:', torch.cuda.device_count()) print('NCCL version:', torch.cuda.nccl.version()) except ImportError: print('Torch version:', None) try: import deepspeed print('DeepSpeed version:', deepspeed.__version__) except ImportError: print('DeepSpeed version:', None) try: import tensorflow as tf print('TensorFlow version:', tf.__version__) print('TF GPUs available:', bool(tf.config.list_physical_devices('GPU'))) print('Number of TF GPUs available:', len(tf.config.list_physical_devices('GPU'))) except ImportError: print('TensorFlow version:', None)
148
1
"""simple docstring""" from typing import Any def __lowerCamelCase ( __UpperCamelCase ) -> list[Any]: """simple docstring""" if not input_list: return [] lowerCAmelCase_ : Any = [input_list.count(__UpperCamelCase ) for value in input_list] lowerCAmelCase_ : List[Any] = max(__UpperCamelCase ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(__UpperCamelCase ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
610
"""simple docstring""" import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCamelCase ( A__ , unittest.TestCase ): '''simple docstring''' a_ : str = GPTaTokenizer a_ : Dict = GPTaTokenizerFast a_ : List[Any] = True a_ : str = {"""add_prefix_space""": True} a_ : Dict = False def lowerCamelCase ( self : Tuple ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase_ : Optional[Any] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] lowerCAmelCase_ : List[Any] = dict(zip(a_ , range(len(a_ ) ) ) ) lowerCAmelCase_ : List[str] = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowerCAmelCase_ : Optional[Any] = {"unk_token": "<unk>"} lowerCAmelCase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowerCAmelCase_ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(a_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(a_ ) ) def lowerCamelCase ( self : Optional[Any] , **a_ : Optional[Any] ): kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **a_ ) def lowerCamelCase ( self : List[Any] , **a_ : int ): kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def lowerCamelCase ( self : Tuple , a_ : Optional[Any] ): lowerCAmelCase_ : str = "lower newer" lowerCAmelCase_ : Dict = "lower newer" return input_text, output_text def lowerCamelCase ( self : int ): lowerCAmelCase_ : Any = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCAmelCase_ : str = "lower newer" lowerCAmelCase_ : List[str] = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] lowerCAmelCase_ : Optional[Any] = tokenizer.tokenize(a_ , add_prefix_space=a_ ) self.assertListEqual(a_ , a_ ) lowerCAmelCase_ : List[Any] = tokens + [tokenizer.unk_token] lowerCAmelCase_ : int = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , a_ ) def lowerCamelCase ( self : str ): if not self.test_rust_tokenizer: return lowerCAmelCase_ : int = self.get_tokenizer() lowerCAmelCase_ : Optional[Any] = self.get_rust_tokenizer(add_prefix_space=a_ ) lowerCAmelCase_ : int = "lower newer" # Testing tokenization lowerCAmelCase_ : Optional[int] = tokenizer.tokenize(a_ , add_prefix_space=a_ ) lowerCAmelCase_ : int = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) # Testing conversion to ids without special tokens lowerCAmelCase_ : List[str] = tokenizer.encode(a_ , add_special_tokens=a_ , add_prefix_space=a_ ) lowerCAmelCase_ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # Testing conversion to ids with special tokens lowerCAmelCase_ : Any = self.get_rust_tokenizer(add_prefix_space=a_ ) lowerCAmelCase_ : List[Any] = tokenizer.encode(a_ , add_prefix_space=a_ ) lowerCAmelCase_ : str = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) # Testing the unknown token lowerCAmelCase_ : List[str] = tokens + [rust_tokenizer.unk_token] lowerCAmelCase_ : Dict = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_ ) , a_ ) def lowerCamelCase ( self : Dict , *a_ : Optional[int] , **a_ : Union[str, Any] ): # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def lowerCamelCase ( self : Optional[int] , a_ : List[Any]=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCAmelCase_ : str = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) # Simple input lowerCAmelCase_ : Optional[int] = "This is a simple input" lowerCAmelCase_ : List[Any] = ["This is a simple input 1", "This is a simple input 2"] lowerCAmelCase_ : List[str] = ("This is a simple input", "This is a pair") lowerCAmelCase_ : List[Any] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(a_ , tokenizer_r.encode , a_ , max_length=a_ , padding="max_length" ) # Simple input self.assertRaises(a_ , tokenizer_r.encode_plus , a_ , max_length=a_ , padding="max_length" ) # Simple input self.assertRaises( a_ , tokenizer_r.batch_encode_plus , a_ , max_length=a_ , padding="max_length" , ) # Pair input self.assertRaises(a_ , tokenizer_r.encode , a_ , max_length=a_ , padding="max_length" ) # Pair input self.assertRaises(a_ , tokenizer_r.encode_plus , a_ , max_length=a_ , padding="max_length" ) # Pair input self.assertRaises( a_ , tokenizer_r.batch_encode_plus , a_ , max_length=a_ , padding="max_length" , ) def lowerCamelCase ( self : Optional[int] ): lowerCAmelCase_ : Optional[int] = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token="<pad>" ) # Simple input lowerCAmelCase_ : Tuple = "This is a simple input" lowerCAmelCase_ : Any = ["This is a simple input looooooooong", "This is a simple input"] lowerCAmelCase_ : Union[str, Any] = ("This is a simple input", "This is a pair") lowerCAmelCase_ : Optional[Any] = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] lowerCAmelCase_ : Dict = tokenizer.pad_token_id lowerCAmelCase_ : Union[str, Any] = tokenizer(a_ , padding="max_length" , max_length=30 , return_tensors="np" ) lowerCAmelCase_ : Tuple = tokenizer(a_ , padding=a_ , truncate=a_ , return_tensors="np" ) lowerCAmelCase_ : Dict = tokenizer(*a_ , padding="max_length" , max_length=60 , return_tensors="np" ) lowerCAmelCase_ : Union[str, Any] = tokenizer(a_ , padding=a_ , truncate=a_ , return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def lowerCamelCase ( self : List[Any] ): lowerCAmelCase_ : Tuple = "$$$" lowerCAmelCase_ : Optional[Any] = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=a_ , add_bos_token=a_ ) lowerCAmelCase_ : Tuple = "This is a simple input" lowerCAmelCase_ : Optional[int] = ["This is a simple input 1", "This is a simple input 2"] lowerCAmelCase_ : Optional[Any] = tokenizer.bos_token_id lowerCAmelCase_ : int = tokenizer(a_ ) lowerCAmelCase_ : Optional[Any] = tokenizer(a_ ) self.assertEqual(out_s.input_ids[0] , a_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) lowerCAmelCase_ : int = tokenizer.decode(out_s.input_ids ) lowerCAmelCase_ : List[Any] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , a_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def lowerCamelCase ( self : List[str] ): pass def lowerCamelCase ( self : List[Any] ): # TODO: change to self.get_tokenizers() when the fast version is implemented lowerCAmelCase_ : int = [self.get_tokenizer(do_lower_case=a_ , add_bos_token=a_ )] for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): lowerCAmelCase_ : Optional[Any] = "Encode this." lowerCAmelCase_ : List[str] = "This one too please." lowerCAmelCase_ : Tuple = tokenizer.encode(a_ , add_special_tokens=a_ ) encoded_sequence += tokenizer.encode(a_ , add_special_tokens=a_ ) lowerCAmelCase_ : Dict = tokenizer.encode_plus( a_ , a_ , add_special_tokens=a_ , return_special_tokens_mask=a_ , ) lowerCAmelCase_ : List[str] = encoded_sequence_dict["input_ids"] lowerCAmelCase_ : Optional[Any] = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(a_ ) , len(a_ ) ) lowerCAmelCase_ : str = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(a_ ) ] lowerCAmelCase_ : List[Any] = [x for x in filtered_sequence if x is not None] self.assertEqual(a_ , a_ ) @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase ( self : str ): # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 lowerCAmelCase_ : List[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=a_ ) lowerCAmelCase_ : List[Any] = "A photo of a cat" lowerCAmelCase_ : Union[str, Any] = tokenizer.encode( a_ , ) self.assertEqual(a_ , [2, 2_50, 13_45, 9, 10, 47_58] ) tokenizer.save_pretrained("test_opt" ) lowerCAmelCase_ : Optional[Any] = AutoTokenizer.from_pretrained("./test_opt" ) lowerCAmelCase_ : Optional[int] = tokenizer.encode( a_ , ) self.assertEqual(a_ , [2, 2_50, 13_45, 9, 10, 47_58] ) def lowerCamelCase ( self : int ): lowerCAmelCase_ : Optional[int] = AutoTokenizer.from_pretrained("facebook/opt-350m" , use_slow=a_ ) lowerCAmelCase_ : Any = "A photo of a cat" lowerCAmelCase_ : List[str] = tokenizer.encode( a_ , ) # Same as above self.assertEqual(a_ , [2, 2_50, 13_45, 9, 10, 47_58] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def lowerCamelCase ( self : List[str] ): lowerCAmelCase_ : List[Any] = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=a_ ) lowerCAmelCase_ : Tuple = "bos" lowerCAmelCase_ : Dict = tokenizer.get_vocab()["bos"] lowerCAmelCase_ : List[Any] = "A photo of a cat" lowerCAmelCase_ : Optional[Any] = tokenizer.encode( a_ , ) # We changed the bos token self.assertEqual(a_ , [3_19_57, 2_50, 13_45, 9, 10, 47_58] ) tokenizer.save_pretrained("./tok" ) lowerCAmelCase_ : str = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) lowerCAmelCase_ : int = tokenizer.encode( a_ , ) self.assertEqual(a_ , [3_19_57, 2_50, 13_45, 9, 10, 47_58] )
610
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 lowerCAmelCase_ ( unittest.TestCase): def _snake_case ( self : Optional[Any] ) ->Tuple: """simple docstring""" a__ :Union[str, Any] = mock.Mock() a__ :Optional[Any] = 500 a__ :Union[str, Any] = {} a__ :List[str] = HTTPError a__ :Union[str, Any] = {} # Download this model to make sure it's in the cache. a__ :Tuple = 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=__A ) as mock_head: a__ :Optional[int] = 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 _snake_case ( self : Any ) ->List[str]: """simple docstring""" a__ :Union[str, Any] = mock.Mock() a__ :str = 500 a__ :Optional[Any] = {} a__ :Dict = HTTPError a__ :List[Any] = {} # Download this model to make sure it's in the cache. a__ :Any = 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=__A ) as mock_head: a__ :Any = GPTaTokenizerFast.from_pretrained("gpt2" ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self : str ) ->Union[str, Any]: """simple docstring""" try: a__ :Optional[int] = tempfile.mktemp() with open(__A , "wb" ) as f: http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , __A ) a__ :Tuple = AlbertTokenizer.from_pretrained(__A ) finally: os.remove(__A ) # 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" , __A ) a__ :Tuple = 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 _snake_case ( self : Union[str, Any] ) ->Any: """simple docstring""" a__ :Optional[Any] = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase): lowerCamelCase_ = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _snake_case ( cls : int ) ->Dict: """simple docstring""" a__ :str = TOKEN HfFolder.save_token(__A ) @classmethod def _snake_case ( cls : Optional[int] ) ->List[Any]: """simple docstring""" 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 _snake_case ( self : List[str] ) ->Any: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: a__ :List[Any] = os.path.join(__A , "vocab.txt" ) with open(__A , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) a__ :Optional[int] = BertTokenizer(__A ) tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token ) a__ :Dict = 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(__A , repo_id="test-tokenizer" , push_to_hub=__A , use_auth_token=self._token ) a__ :Union[str, Any] = BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def _snake_case ( self : Dict ) ->int: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: a__ :Optional[Any] = os.path.join(__A , "vocab.txt" ) with open(__A , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) a__ :List[Any] = BertTokenizer(__A ) tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token ) a__ :str = 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( __A , repo_id="valid_org/test-tokenizer-org" , push_to_hub=__A , use_auth_token=self._token ) a__ :Optional[int] = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def _snake_case ( self : Optional[int] ) ->List[Any]: """simple docstring""" CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: a__ :Any = os.path.join(__A , "vocab.txt" ) with open(__A , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) a__ :Optional[Any] = CustomTokenizer(__A ) # No fast custom tokenizer tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) a__ :Optional[int] = AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=__A ) # 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: a__ :Union[str, Any] = os.path.join(__A , "vocab.txt" ) with open(__A , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) a__ :Dict = BertTokenizerFast.from_pretrained(__A ) bert_tokenizer.save_pretrained(__A ) a__ :Optional[int] = CustomTokenizerFast.from_pretrained(__A ) tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) a__ :Tuple = AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=__A ) # 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" ) a__ :Tuple = AutoTokenizer.from_pretrained( F'''{USER}/test-dynamic-tokenizer''' , use_fast=__A , trust_remote_code=__A ) # 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 lowerCAmelCase_ ( unittest.TestCase): def _snake_case ( self : int ) ->List[Any]: """simple docstring""" a__ :List[str] = 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 _snake_case ( self : Union[str, Any] ) ->str: """simple docstring""" a__ :Optional[Any] = 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 _snake_case ( self : Tuple ) ->List[str]: """simple docstring""" a__ :str = Trie() trie.add("A" ) self.assertEqual(trie.split("ABC" ) , ["A", "BC"] ) self.assertEqual(trie.split("BCA" ) , ["BC", "A"] ) def _snake_case ( self : Union[str, Any] ) ->List[str]: """simple docstring""" a__ :int = Trie() trie.add("TOKEN]" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def _snake_case ( self : str ) ->str: """simple docstring""" a__ :List[Any] = 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 _snake_case ( self : List[str] ) ->Any: """simple docstring""" a__ :Union[str, Any] = Trie() trie.add("AB" ) trie.add("B" ) trie.add("C" ) self.assertEqual(trie.split("ABC" ) , ["AB", "C"] ) def _snake_case ( self : Optional[Any] ) ->str: """simple docstring""" a__ :int = Trie() trie.add("ABC" ) trie.add("B" ) trie.add("CD" ) self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] ) def _snake_case ( self : Tuple ) ->List[str]: """simple docstring""" a__ :List[str] = Trie() a__ :str = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] ) self.assertEqual(__A , ["AB", "C"] )
373
def lowerCamelCase__ ( a : list[list] ) -> list[list]: """simple docstring""" a__ :Any = current_set.copy() for row_index, row in enumerate(a ): a__ :List[str] = row[0] for column_index, column in enumerate(a ): if magnitude == 0: a__ :Tuple = column continue a__ :Tuple = column / magnitude # Subtract to cancel term a__ :Any = current_set[0] a__ :Dict = [first_row] a__ :Dict = current_set[1::] for row in current_set: a__ :int = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(a ) continue for column_index in range(len(a ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(a ) # Create next recursion iteration set if len(final_set[0] ) != 3: a__ :List[str] = final_set[0] a__ :Optional[Any] = [] a__ :List[Any] = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) a__ :Dict = simplify(a ) for i in range(len(a ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , a ) a__ :Optional[int] = resultant return final_set def lowerCamelCase__ ( a : list[list] ) -> list: """simple docstring""" if len(a ) == 0: raise IndexError("solve_simultaneous() requires n lists of length n+1" ) a__ :Any = len(a ) + 1 if any(len(a ) != _length for item in equations ): raise IndexError("solve_simultaneous() requires n lists of length n+1" ) for row in equations: if any(not isinstance(a , (int, float) ) for column in row ): raise ValueError("solve_simultaneous() requires lists of integers" ) if len(a ) == 1: return [equations[0][-1] / equations[0][0]] a__ :Union[str, Any] = equations.copy() if any(0 in row for row in data_set ): a__ :int = data_set.copy() a__ :Dict = [] for row_index, row in enumerate(a ): if 0 not in row: a__ :Union[str, Any] = data_set.pop(a ) break if not full_row: raise ValueError("solve_simultaneous() requires at least 1 full equation" ) data_set.insert(0 , a ) a__ :Optional[int] = data_set.copy() a__ :Any = simplify(a ) a__ :str = simplified[::-1] a__ :list = [] for row in simplified: a__ :Optional[int] = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue a__ :Dict = row.copy()[: len(a ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(a ) == 0: solutions.append(0 ) continue a__ :List[Any] = temp_row[1::] a__ :Union[str, Any] = temp_row[::-1] for column_index, column in enumerate(a ): current_solution -= column * solutions[column_index] solutions.append(a ) a__ :List[str] = [] for item in solutions: final.append(float(round(a , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() snake_case__ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
373
1
"""simple docstring""" import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , _lowercase , _lowercase=1_3 , _lowercase=7 , _lowercase=True , _lowercase=True , _lowercase=True , _lowercase=True , _lowercase=9_9 , _lowercase=3_2 , _lowercase=5 , _lowercase=4 , _lowercase=3_7 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=5_1_2 , _lowercase=1_6 , _lowercase=2 , _lowercase=0.02 , _lowercase=4 , ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : List[Any] = batch_size snake_case_ : str = seq_length snake_case_ : List[str] = is_training snake_case_ : Optional[int] = use_attention_mask snake_case_ : str = use_token_type_ids snake_case_ : List[str] = use_labels snake_case_ : Union[str, Any] = vocab_size snake_case_ : List[Any] = hidden_size snake_case_ : List[str] = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : Dict = intermediate_size snake_case_ : Optional[Any] = hidden_act snake_case_ : Optional[Any] = hidden_dropout_prob snake_case_ : List[str] = attention_probs_dropout_prob snake_case_ : Tuple = max_position_embeddings snake_case_ : int = type_vocab_size snake_case_ : Optional[Any] = type_sequence_label_size snake_case_ : Optional[Any] = initializer_range snake_case_ : List[str] = num_choices def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ : Tuple = None if self.use_attention_mask: snake_case_ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ : Tuple = None if self.use_token_type_ids: snake_case_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ : Any = RobertaPreLayerNormConfig( 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=_lowercase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ : str = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ : List[Any] = config_and_inputs snake_case_ : Any = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def UpperCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ : Optional[int] = config_and_inputs snake_case_ : Union[str, Any] = True snake_case_ : Optional[Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) snake_case_ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" _lowerCamelCase = True _lowerCamelCase = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ : str = FlaxRobertaPreLayerNormModelTester(self ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' for model_class_name in self.all_model_classes: snake_case_ : Optional[int] = model_class_name.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=_lowercase ) snake_case_ : List[str] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowercase ) @require_flax class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=_lowercase ) snake_case_ : str = np.array([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] , dtype=jnp.intaa ) snake_case_ : Dict = model(_lowercase )[0] snake_case_ : Optional[Any] = [1, 1_1, 5_0_2_6_5] self.assertEqual(list(output.shape ) , _lowercase ) # compare the actual values for a slice. snake_case_ : Tuple = np.array( [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , _lowercase , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ : Optional[int] = FlaxRobertaPreLayerNormModel.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=_lowercase ) snake_case_ : Union[str, Any] = np.array([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] , dtype=jnp.intaa ) snake_case_ : Dict = model(_lowercase )[0] # compare the actual values for a slice. snake_case_ : List[str] = np.array( [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , _lowercase , atol=1E-4 ) )
58
"""simple docstring""" from collections.abc import Callable import numpy as np def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> np.ndarray: """simple docstring""" _UpperCamelCase : List[str] = int(np.ceil((x_end - xa) / step_size ) ) _UpperCamelCase : Tuple = np.zeros((n + 1,) ) _UpperCamelCase : List[str] = ya _UpperCamelCase : List[Any] = xa for k in range(lowercase_ ): _UpperCamelCase : List[str] = y[k] + step_size * ode_func(lowercase_ ,y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
624
0
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( __A , unittest.TestCase ): '''simple docstring''' _lowercase = OpenAIGPTTokenizer _lowercase = OpenAIGPTTokenizerFast _lowercase = True _lowercase = False def __lowerCamelCase ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ : str =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] SCREAMING_SNAKE_CASE_ : Optional[int] =dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE_ : str =['#version: 0.2', 'l o', 'lo w', 'e r</w>', ''] SCREAMING_SNAKE_CASE_ : List[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE_ : List[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(__UpperCAmelCase ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(__UpperCAmelCase ) ) def __lowerCamelCase ( self , __UpperCAmelCase ): return "lower newer", "lower newer" def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : List[str] =OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE_ : str ='lower' SCREAMING_SNAKE_CASE_ : str =['low', 'er</w>'] SCREAMING_SNAKE_CASE_ : List[Any] =tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Any =tokens + ['<unk>'] SCREAMING_SNAKE_CASE_ : Any =[14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , __UpperCAmelCase ) def __lowerCamelCase ( self , __UpperCAmelCase=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): SCREAMING_SNAKE_CASE_ : str =self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) # Simple input SCREAMING_SNAKE_CASE_ : Any ='This is a simple input' SCREAMING_SNAKE_CASE_ : Union[str, Any] =['This is a simple input 1', 'This is a simple input 2'] SCREAMING_SNAKE_CASE_ : Union[str, Any] =('This is a simple input', 'This is a pair') SCREAMING_SNAKE_CASE_ : Optional[Any] =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(__UpperCAmelCase , tokenizer_r.encode , __UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' ) # Simple input self.assertRaises(__UpperCAmelCase , tokenizer_r.encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' ) # Simple input self.assertRaises( __UpperCAmelCase , tokenizer_r.batch_encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' , ) # Pair input self.assertRaises(__UpperCAmelCase , tokenizer_r.encode , __UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' ) # Pair input self.assertRaises(__UpperCAmelCase , tokenizer_r.encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' ) # Pair input self.assertRaises( __UpperCAmelCase , tokenizer_r.batch_encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' , ) def __lowerCamelCase ( self ): pass @require_ftfy @require_spacy @require_tokenizers class lowerCAmelCase_ ( __A ): '''simple docstring''' pass
721
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class lowerCAmelCase_ ( __A , unittest.TestCase ): '''simple docstring''' _lowercase = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def __lowerCamelCase ( self , __UpperCAmelCase=0 ): SCREAMING_SNAKE_CASE_ : Dict =floats_tensor((1, 3, 128, 128) , rng=random.Random(__UpperCAmelCase ) ) SCREAMING_SNAKE_CASE_ : Tuple =np.random.RandomState(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : str ={ 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Any =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple =self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : List[Any] =pipe(**__UpperCAmelCase ).images SCREAMING_SNAKE_CASE_ : str =image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] =np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Tuple =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE_ : int =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : int =self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : str =pipe(**__UpperCAmelCase ).images SCREAMING_SNAKE_CASE_ : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] =np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Optional[Any] =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE_ : List[Any] =LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # warmup pass to apply optimizations SCREAMING_SNAKE_CASE_ : Union[str, Any] =pipe(**self.get_dummy_inputs() ) SCREAMING_SNAKE_CASE_ : int =self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Any =pipe(**__UpperCAmelCase ).images SCREAMING_SNAKE_CASE_ : Any =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE_ : Optional[int] =np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : str =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE_ : int =EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : List[str] =self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] =pipe(**__UpperCAmelCase ).images SCREAMING_SNAKE_CASE_ : List[str] =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE_ : Optional[Any] =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : List[str] =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE_ : str =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : str =self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Optional[int] =pipe(**__UpperCAmelCase ).images SCREAMING_SNAKE_CASE_ : Union[str, Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE_ : Any =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Optional[Any] =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) SCREAMING_SNAKE_CASE_ : Optional[Any] =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : List[Any] =self.get_dummy_inputs() SCREAMING_SNAKE_CASE_ : Dict =pipe(**__UpperCAmelCase ).images SCREAMING_SNAKE_CASE_ : List[str] =image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE_ : Any =np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @property def __lowerCamelCase ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Optional[Any] =ort.SessionOptions() SCREAMING_SNAKE_CASE_ : int =False return options def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Tuple =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) SCREAMING_SNAKE_CASE_ : Optional[Any] =init_image.resize((768, 512) ) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE_ : Optional[int] =OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple ='A fantasy landscape, trending on artstation' SCREAMING_SNAKE_CASE_ : Dict =np.random.RandomState(0 ) SCREAMING_SNAKE_CASE_ : Tuple =pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__UpperCAmelCase , output_type='np' , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =output.images SCREAMING_SNAKE_CASE_ : Union[str, Any] =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) SCREAMING_SNAKE_CASE_ : Union[str, Any] =np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def __lowerCamelCase ( self ): SCREAMING_SNAKE_CASE_ : Tuple =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =init_image.resize((768, 512) ) SCREAMING_SNAKE_CASE_ : Tuple =LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) SCREAMING_SNAKE_CASE_ : Optional[Any] =OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ : List[Any] ='A fantasy landscape, trending on artstation' SCREAMING_SNAKE_CASE_ : int =np.random.RandomState(0 ) SCREAMING_SNAKE_CASE_ : Optional[Any] =pipe( prompt=__UpperCAmelCase , image=__UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__UpperCAmelCase , output_type='np' , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] =output.images SCREAMING_SNAKE_CASE_ : List[str] =images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) SCREAMING_SNAKE_CASE_ : Dict =np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
153
0
'''simple docstring''' import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class lowercase_ (unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) __lowercase = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(lowercase__ ) __lowercase = -1 __lowercase = ids_tensor((1, 5) ,vocab_size=model.config.vocab_size ).to(lowercase__ ) __lowercase = model.generate(lowercase__ ,max_new_tokens=1_0 ,do_sample=lowercase__ ) __lowercase = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: __lowercase = TextStreamer(lowercase__ ) model.generate(lowercase__ ,max_new_tokens=1_0 ,do_sample=lowercase__ ,streamer=lowercase__ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __lowercase = cs.out[:-1] self.assertEqual(lowercase__ ,lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) __lowercase = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(lowercase__ ) __lowercase = -1 __lowercase = ids_tensor((1, 5) ,vocab_size=model.config.vocab_size ).to(lowercase__ ) __lowercase = model.generate(lowercase__ ,max_new_tokens=1_0 ,do_sample=lowercase__ ) __lowercase = tokenizer.decode(greedy_ids[0] ) __lowercase = TextIteratorStreamer(lowercase__ ) __lowercase = {'''input_ids''': input_ids, '''max_new_tokens''': 1_0, '''do_sample''': False, '''streamer''': streamer} __lowercase = Thread(target=model.generate ,kwargs=lowercase__ ) thread.start() __lowercase = '''''' for new_text in streamer: streamer_text += new_text self.assertEqual(lowercase__ ,lowercase__ ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) __lowercase = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(lowercase__ ) __lowercase = -1 __lowercase = ids_tensor((1, 5) ,vocab_size=model.config.vocab_size ).to(lowercase__ ) __lowercase = model.generate(lowercase__ ,max_new_tokens=1_0 ,do_sample=lowercase__ ) __lowercase = greedy_ids[:, input_ids.shape[1] :] __lowercase = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: __lowercase = TextStreamer(lowercase__ ,skip_prompt=lowercase__ ) model.generate(lowercase__ ,max_new_tokens=1_0 ,do_sample=lowercase__ ,streamer=lowercase__ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __lowercase = cs.out[:-1] self.assertEqual(lowercase__ ,lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them __lowercase = AutoTokenizer.from_pretrained('''distilgpt2''' ) __lowercase = AutoModelForCausalLM.from_pretrained('''distilgpt2''' ).to(lowercase__ ) __lowercase = -1 __lowercase = torch.ones((1, 5) ,device=lowercase__ ).long() * model.config.bos_token_id with CaptureStdout() as cs: __lowercase = TextStreamer(lowercase__ ,skip_special_tokens=lowercase__ ) model.generate(lowercase__ ,max_new_tokens=1 ,do_sample=lowercase__ ,streamer=lowercase__ ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token __lowercase = cs.out[:-1] # Remove the final "\n" __lowercase = tokenizer(lowercase__ ,return_tensors='''pt''' ) self.assertEqual(streamer_text_tokenized.input_ids.shape ,(1, 1) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) __lowercase = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(lowercase__ ) __lowercase = -1 __lowercase = ids_tensor((1, 5) ,vocab_size=model.config.vocab_size ).to(lowercase__ ) __lowercase = TextIteratorStreamer(lowercase__ ,timeout=0.0_0_1 ) __lowercase = {'''input_ids''': input_ids, '''max_new_tokens''': 1_0, '''do_sample''': False, '''streamer''': streamer} __lowercase = Thread(target=model.generate ,kwargs=lowercase__ ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(lowercase__ ): __lowercase = '''''' for new_text in streamer: streamer_text += new_text
41
'''simple docstring''' from __future__ import annotations UpperCamelCase__: Tuple = 1.60_21E-19 # units = C def snake_case_ ( _lowerCAmelCase : float , _lowerCAmelCase : float , _lowerCAmelCase : float , ) -> tuple[str, float]: if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif conductivity < 0: raise ValueError('''Conductivity cannot be negative''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative''' ) elif mobility < 0: raise ValueError('''mobility cannot be negative''' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
127
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class _snake_case ( __snake_case ): """simple docstring""" a = "blip_text_model" def __init__( self : Optional[int] , _A : Dict=3_0_5_2_4 , _A : Union[str, Any]=7_6_8 , _A : Optional[int]=7_6_8 , _A : Tuple=3_0_7_2 , _A : List[Any]=7_6_8 , _A : Tuple=1_2 , _A : Tuple=8 , _A : List[str]=5_1_2 , _A : Optional[Any]="gelu" , _A : Optional[Any]=1e-12 , _A : Optional[Any]=0.0 , _A : str=0.0 , _A : List[Any]=0.02 , _A : int=3_0_5_2_2 , _A : Union[str, Any]=2 , _A : List[Any]=0 , _A : str=1_0_2 , _A : int=True , _A : Tuple=True , **_A : List[str] , ): """simple docstring""" super().__init__( pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , sep_token_id=_UpperCAmelCase , **_UpperCAmelCase , ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = encoder_hidden_size _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = projection_dim _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = is_decoder _SCREAMING_SNAKE_CASE = use_cache @classmethod def _lowerCAmelCase ( cls : Any , _A : Union[str, os.PathLike] , **_A : Optional[Any]): """simple docstring""" cls._set_token_in_kwargs(_UpperCAmelCase) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase) # get the text config dict if we are loading from BlipConfig if config_dict.get("""model_type""") == "blip": _SCREAMING_SNAKE_CASE = config_dict["""text_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(_UpperCAmelCase , **_UpperCAmelCase) class _snake_case ( __snake_case ): """simple docstring""" a = "blip_vision_model" def __init__( self : Optional[int] , _A : List[Any]=7_6_8 , _A : Dict=3_0_7_2 , _A : Any=5_1_2 , _A : Optional[Any]=1_2 , _A : List[Any]=1_2 , _A : List[str]=3_8_4 , _A : Optional[Any]=1_6 , _A : Tuple="gelu" , _A : Optional[Any]=1e-5 , _A : int=0.0 , _A : Union[str, Any]=1e-10 , **_A : Optional[Any] , ): """simple docstring""" super().__init__(**_UpperCAmelCase) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = projection_dim _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 @classmethod def _lowerCAmelCase ( cls : str , _A : Union[str, os.PathLike] , **_A : List[str]): """simple docstring""" cls._set_token_in_kwargs(_UpperCAmelCase) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase) # get the vision config dict if we are loading from BlipConfig if config_dict.get("""model_type""") == "blip": _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(_UpperCAmelCase , **_UpperCAmelCase) class _snake_case ( __snake_case ): """simple docstring""" a = "blip" a = True def __init__( self : Tuple , _A : Any=None , _A : List[str]=None , _A : int=5_1_2 , _A : Dict=2.6_592 , _A : int=2_5_6 , **_A : str , ): """simple docstring""" super().__init__(**_UpperCAmelCase) if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BlipTextConfig` with default values.""") if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.""") _SCREAMING_SNAKE_CASE = BlipTextConfig(**_UpperCAmelCase) _SCREAMING_SNAKE_CASE = BlipVisionConfig(**_UpperCAmelCase) _SCREAMING_SNAKE_CASE = self.vision_config.hidden_size _SCREAMING_SNAKE_CASE = projection_dim _SCREAMING_SNAKE_CASE = logit_scale_init_value _SCREAMING_SNAKE_CASE = 1.0 _SCREAMING_SNAKE_CASE = 0.02 _SCREAMING_SNAKE_CASE = image_text_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] , _A : BlipTextConfig , _A : BlipVisionConfig , **_A : Any): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_UpperCAmelCase) def _lowerCAmelCase ( self : Union[str, Any]): """simple docstring""" _SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__) _SCREAMING_SNAKE_CASE = self.text_config.to_dict() _SCREAMING_SNAKE_CASE = self.vision_config.to_dict() _SCREAMING_SNAKE_CASE = self.__class__.model_type return output
714
"""simple docstring""" from __future__ import annotations def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , )-> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
635
0
from ..utils import DummyObject, requires_backends class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Union[str, Any] , *_lowerCAmelCase : int , **_lowerCAmelCase : List[Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Any , **_lowerCAmelCase : int ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Union[str, Any] , *_lowerCAmelCase : Any , **_lowerCAmelCase : Tuple ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Any , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Optional[int] , *_lowerCAmelCase : List[Any] , **_lowerCAmelCase : Any ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Any , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Any ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Optional[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Any , **_lowerCAmelCase : Optional[int] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : int , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : int ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Tuple , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Optional[int] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Dict , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : str , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : List[str] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : List[str] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Tuple , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : Optional[Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : List[Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Any , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Optional[Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Any , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Optional[int] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : Any ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Union[str, Any] ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : int , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : Tuple ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : str , **_lowerCAmelCase : Union[str, Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[str] , *_lowerCAmelCase : Tuple , **_lowerCAmelCase : int ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Union[str, Any] , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : Dict ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : int , *_lowerCAmelCase : int , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : int , *_lowerCAmelCase : Any , **_lowerCAmelCase : Dict ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Optional[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : int , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] ) class lowerCamelCase_ ( metaclass=UpperCAmelCase_ ): '''simple docstring''' lowercase_ = ['''flax'''] def __init__( self : List[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Tuple ): requires_backends(self , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : List[str] , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : Optional[Any] ): requires_backends(cls , ['flax'] ) @classmethod def lowerCAmelCase_ ( cls : Dict , *_lowerCAmelCase : Union[str, Any] , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ['flax'] )
31
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase : str = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowerCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
671
0
'''simple docstring''' lowercase =[sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def lowerCamelCase__ ( __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : List[str] =0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 1_0_0_0_0_0] number //= 1_0_0_0_0_0 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowercase =[None] * 10000000 lowercase =True lowercase =False def lowerCamelCase__ ( __lowerCamelCase : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore _UpperCAmelCase : Union[str, Any] =chain(next_number(__lowerCamelCase ) ) _UpperCAmelCase : int =number_chain while number < 1_0_0_0_0_0_0_0: _UpperCAmelCase : Optional[Any] =number_chain number *= 1_0 return number_chain def lowerCamelCase__ ( __lowerCamelCase : int = 1_0_0_0_0_0_0_0 ): '''simple docstring''' for i in range(1 , __lowerCamelCase ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution() = }""")
713
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset from utils import logger class __magic_name__ ( lowerCAmelCase ): def __init__( self , snake_case , snake_case) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : Dict =params _UpperCAmelCase : List[Any] =np.array(snake_case) _UpperCAmelCase : Tuple =np.array([len(snake_case) for t in data]) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , snake_case) -> str: '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self) -> Any: '''simple docstring''' return len(self.lengths) def lowerCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' assert len(self.token_ids) == len(self.lengths) assert all(self.lengths[i] == len(self.token_ids[i]) for i in range(len(self.lengths))) def lowerCAmelCase ( self) -> str: '''simple docstring''' _UpperCAmelCase : List[str] =self.params.max_model_input_size _UpperCAmelCase : List[str] =self.lengths > max_len logger.info(f"Splitting {sum(snake_case)} too long sequences.") def divide_chunks(snake_case , snake_case): return [l[i : i + n] for i in range(0 , len(snake_case) , snake_case)] _UpperCAmelCase : Dict =[] _UpperCAmelCase : str =[] if self.params.mlm: _UpperCAmelCase , _UpperCAmelCase : Any =self.params.special_tok_ids['cls_token'], self.params.special_tok_ids['sep_token'] else: _UpperCAmelCase , _UpperCAmelCase : str =self.params.special_tok_ids['bos_token'], self.params.special_tok_ids['eos_token'] for seq_, len_ in zip(self.token_ids , self.lengths): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_) new_lengths.append(len_) else: _UpperCAmelCase : List[Any] =[] for sub_s in divide_chunks(seq_ , max_len - 2): if sub_s[0] != cls_id: _UpperCAmelCase : List[Any] =np.insert(snake_case , 0 , snake_case) if sub_s[-1] != sep_id: _UpperCAmelCase : str =np.insert(snake_case , len(snake_case) , snake_case) assert len(snake_case) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(snake_case) new_tok_ids.extend(snake_case) new_lengths.extend([len(snake_case) for l in sub_seqs]) _UpperCAmelCase : List[str] =np.array(snake_case) _UpperCAmelCase : Optional[Any] =np.array(snake_case) def lowerCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : str =len(self) _UpperCAmelCase : List[Any] =self.lengths > 1_1 _UpperCAmelCase : Tuple =self.token_ids[indices] _UpperCAmelCase : Tuple =self.lengths[indices] _UpperCAmelCase : Union[str, Any] =len(self) logger.info(f"Remove {init_size - new_size} too short (<=11 tokens) sequences.") def lowerCAmelCase ( self) -> Any: '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: _UpperCAmelCase : int =self.params.special_tok_ids['unk_token'] _UpperCAmelCase : int =len(self) _UpperCAmelCase : int =np.array([np.count_nonzero(a == unk_token_id) for a in self.token_ids]) _UpperCAmelCase : Optional[int] =(unk_occs / self.lengths) < 0.5 _UpperCAmelCase : str =self.token_ids[indices] _UpperCAmelCase : Optional[int] =self.lengths[indices] _UpperCAmelCase : Optional[Any] =len(self) logger.info(f"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).") def lowerCAmelCase ( self) -> int: '''simple docstring''' if not self.params.is_master: return logger.info(f"{len(self)} sequences") # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def lowerCAmelCase ( self , snake_case) -> int: '''simple docstring''' _UpperCAmelCase : int =[t[0] for t in batch] _UpperCAmelCase : Tuple =[t[1] for t in batch] assert len(snake_case) == len(snake_case) # Max for paddings _UpperCAmelCase : Dict =max(snake_case) # Pad token ids if self.params.mlm: _UpperCAmelCase : str =self.params.special_tok_ids['pad_token'] else: _UpperCAmelCase : str =self.params.special_tok_ids['unk_token'] _UpperCAmelCase : Dict =[list(t.astype(snake_case)) + [pad_idx] * (max_seq_len_ - len(snake_case)) for t in token_ids] assert len(tk_) == len(snake_case) assert all(len(snake_case) == max_seq_len_ for t in tk_) _UpperCAmelCase : List[Any] =torch.tensor(tk_) # (bs, max_seq_len_) _UpperCAmelCase : int =torch.tensor(snake_case) # (bs) return tk_t, lg_t
331
0
'''simple docstring''' from torch import nn class __lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : Any , lowerCAmelCase : Any , lowerCAmelCase : int ): super().__init__() A_ = class_size A_ = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) A_ = nn.Linear(lowerCAmelCase , lowerCAmelCase ) def _UpperCAmelCase ( self : Union[str, Any] , lowerCAmelCase : int ): # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) A_ = self.mlp(lowerCAmelCase ) return logits
452
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __lowerCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase : torch.FloatTensor class __lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : str , lowerCAmelCase : Tuple=3 , lowerCAmelCase : Union[str, Any]=3 , lowerCAmelCase : str=("DownEncoderBlock2D",) , lowerCAmelCase : Union[str, Any]=(64,) , lowerCAmelCase : str=2 , lowerCAmelCase : List[Any]=32 , lowerCAmelCase : List[str]="silu" , lowerCAmelCase : Tuple=True , ): super().__init__() A_ = layers_per_block A_ = torch.nn.Convad( lowerCAmelCase , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) A_ = None A_ = nn.ModuleList([] ) # down A_ = block_out_channels[0] for i, down_block_type in enumerate(lowerCAmelCase ): A_ = output_channel A_ = block_out_channels[i] A_ = i == len(lowerCAmelCase ) - 1 A_ = get_down_block( lowerCAmelCase , num_layers=self.layers_per_block , in_channels=lowerCAmelCase , out_channels=lowerCAmelCase , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=lowerCAmelCase , resnet_groups=lowerCAmelCase , attention_head_dim=lowerCAmelCase , temb_channels=lowerCAmelCase , ) self.down_blocks.append(lowerCAmelCase ) # mid A_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=lowerCAmelCase , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=lowerCAmelCase , temb_channels=lowerCAmelCase , ) # out A_ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=lowerCAmelCase , eps=1e-6 ) A_ = nn.SiLU() A_ = 2 * out_channels if double_z else out_channels A_ = nn.Convad(block_out_channels[-1] , lowerCAmelCase , 3 , padding=1 ) A_ = False def _UpperCAmelCase ( self : Dict , lowerCAmelCase : int ): A_ = x A_ = self.conv_in(lowerCAmelCase ) if self.training and self.gradient_checkpointing: def create_custom_forward(lowerCAmelCase : Dict ): def custom_forward(*lowerCAmelCase : List[Any] ): return module(*lowerCAmelCase ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: A_ = torch.utils.checkpoint.checkpoint( create_custom_forward(lowerCAmelCase ) , lowerCAmelCase , use_reentrant=lowerCAmelCase ) # middle A_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , lowerCAmelCase , use_reentrant=lowerCAmelCase ) else: for down_block in self.down_blocks: A_ = torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCAmelCase ) , lowerCAmelCase ) # middle A_ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , lowerCAmelCase ) else: # down for down_block in self.down_blocks: A_ = down_block(lowerCAmelCase ) # middle A_ = self.mid_block(lowerCAmelCase ) # post-process A_ = self.conv_norm_out(lowerCAmelCase ) A_ = self.conv_act(lowerCAmelCase ) A_ = self.conv_out(lowerCAmelCase ) return sample class __lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : Optional[int] , lowerCAmelCase : Optional[Any]=3 , lowerCAmelCase : Dict=3 , lowerCAmelCase : Dict=("UpDecoderBlock2D",) , lowerCAmelCase : Optional[int]=(64,) , lowerCAmelCase : str=2 , lowerCAmelCase : Dict=32 , lowerCAmelCase : Any="silu" , lowerCAmelCase : List[Any]="group" , ): super().__init__() A_ = layers_per_block A_ = nn.Convad( lowerCAmelCase , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) A_ = None A_ = nn.ModuleList([] ) A_ = in_channels if norm_type == "spatial" else None # mid A_ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=lowerCAmelCase , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=lowerCAmelCase , temb_channels=lowerCAmelCase , ) # up A_ = list(reversed(lowerCAmelCase ) ) A_ = reversed_block_out_channels[0] for i, up_block_type in enumerate(lowerCAmelCase ): A_ = output_channel A_ = reversed_block_out_channels[i] A_ = i == len(lowerCAmelCase ) - 1 A_ = get_up_block( lowerCAmelCase , num_layers=self.layers_per_block + 1 , in_channels=lowerCAmelCase , out_channels=lowerCAmelCase , prev_output_channel=lowerCAmelCase , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=lowerCAmelCase , resnet_groups=lowerCAmelCase , attention_head_dim=lowerCAmelCase , temb_channels=lowerCAmelCase , resnet_time_scale_shift=lowerCAmelCase , ) self.up_blocks.append(lowerCAmelCase ) A_ = output_channel # out if norm_type == "spatial": A_ = SpatialNorm(block_out_channels[0] , lowerCAmelCase ) else: A_ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=lowerCAmelCase , eps=1e-6 ) A_ = nn.SiLU() A_ = nn.Convad(block_out_channels[0] , lowerCAmelCase , 3 , padding=1 ) A_ = False def _UpperCAmelCase ( self : str , lowerCAmelCase : str , lowerCAmelCase : Union[str, Any]=None ): A_ = z A_ = self.conv_in(lowerCAmelCase ) A_ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(lowerCAmelCase : Union[str, Any] ): def custom_forward(*lowerCAmelCase : Union[str, Any] ): return module(*lowerCAmelCase ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle A_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , lowerCAmelCase , lowerCAmelCase , use_reentrant=lowerCAmelCase ) A_ = sample.to(lowerCAmelCase ) # up for up_block in self.up_blocks: A_ = torch.utils.checkpoint.checkpoint( create_custom_forward(lowerCAmelCase ) , lowerCAmelCase , lowerCAmelCase , use_reentrant=lowerCAmelCase ) else: # middle A_ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , lowerCAmelCase , lowerCAmelCase ) A_ = sample.to(lowerCAmelCase ) # up for up_block in self.up_blocks: A_ = torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCAmelCase ) , lowerCAmelCase , lowerCAmelCase ) else: # middle A_ = self.mid_block(lowerCAmelCase , lowerCAmelCase ) A_ = sample.to(lowerCAmelCase ) # up for up_block in self.up_blocks: A_ = up_block(lowerCAmelCase , lowerCAmelCase ) # post-process if latent_embeds is None: A_ = self.conv_norm_out(lowerCAmelCase ) else: A_ = self.conv_norm_out(lowerCAmelCase , lowerCAmelCase ) A_ = self.conv_act(lowerCAmelCase ) A_ = self.conv_out(lowerCAmelCase ) return sample class __lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[str]=None , lowerCAmelCase : str="random" , lowerCAmelCase : Union[str, Any]=False , lowerCAmelCase : Optional[Any]=True ): super().__init__() A_ = n_e A_ = vq_embed_dim A_ = beta A_ = legacy A_ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) A_ = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) A_ = self.used.shape[0] A_ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A_ = self.re_embed A_ = self.re_embed + 1 print( F"Remapping {self.n_e} indices to {self.re_embed} indices. " F"Using {self.unknown_index} for unknown indices." ) else: A_ = n_e A_ = sane_index_shape def _UpperCAmelCase ( self : int , lowerCAmelCase : Union[str, Any] ): A_ = inds.shape assert len(lowerCAmelCase ) > 1 A_ = inds.reshape(ishape[0] , -1 ) A_ = self.used.to(lowerCAmelCase ) A_ = (inds[:, :, None] == used[None, None, ...]).long() A_ = match.argmax(-1 ) A_ = match.sum(2 ) < 1 if self.unknown_index == "random": A_ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: A_ = self.unknown_index return new.reshape(lowerCAmelCase ) def _UpperCAmelCase ( self : List[Any] , lowerCAmelCase : Tuple ): A_ = inds.shape assert len(lowerCAmelCase ) > 1 A_ = inds.reshape(ishape[0] , -1 ) A_ = self.used.to(lowerCAmelCase ) if self.re_embed > self.used.shape[0]: # extra token A_ = 0 # simply set to zero A_ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , lowerCAmelCase ) return back.reshape(lowerCAmelCase ) def _UpperCAmelCase ( self : int , lowerCAmelCase : List[Any] ): # reshape z -> (batch, height, width, channel) and flatten A_ = z.permute(0 , 2 , 3 , 1 ).contiguous() A_ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A_ = torch.argmin(torch.cdist(lowerCAmelCase , self.embedding.weight ) , dim=1 ) A_ = self.embedding(lowerCAmelCase ).view(z.shape ) A_ = None A_ = None # compute loss for embedding if not self.legacy: A_ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A_ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A_ = z + (z_q - z).detach() # reshape back to match original input shape A_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: A_ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis A_ = self.remap_to_used(lowerCAmelCase ) A_ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: A_ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _UpperCAmelCase ( self : str , lowerCAmelCase : int , lowerCAmelCase : int ): # shape specifying (batch, height, width, channel) if self.remap is not None: A_ = indices.reshape(shape[0] , -1 ) # add batch axis A_ = self.unmap_to_all(lowerCAmelCase ) A_ = indices.reshape(-1 ) # flatten again # get quantized latent vectors A_ = self.embedding(lowerCAmelCase ) if shape is not None: A_ = z_q.view(lowerCAmelCase ) # reshape back to match original input shape A_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __lowerCAmelCase ( lowercase ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any]=False ): A_ = parameters A_ , A_ = torch.chunk(lowerCAmelCase , 2 , dim=1 ) A_ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) A_ = deterministic A_ = torch.exp(0.5 * self.logvar ) A_ = torch.exp(self.logvar ) if self.deterministic: A_ = A_ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def _UpperCAmelCase ( self : List[str] , lowerCAmelCase : Optional[torch.Generator] = None ): # make sure sample is on the same device as the parameters and has same dtype A_ = randn_tensor( self.mean.shape , generator=lowerCAmelCase , device=self.parameters.device , dtype=self.parameters.dtype ) A_ = self.mean + self.std * sample return x def _UpperCAmelCase ( self : Optional[int] , lowerCAmelCase : str=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def _UpperCAmelCase ( self : List[Any] , lowerCAmelCase : int , lowerCAmelCase : Optional[int]=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) A_ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=lowerCAmelCase ) def _UpperCAmelCase ( self : Union[str, Any] ): return self.mean
452
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : str ='''▁''' __SCREAMING_SNAKE_CASE : Union[str, Any] ={'''vocab_file''': '''spiece.model'''} __SCREAMING_SNAKE_CASE : str ={ '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } __SCREAMING_SNAKE_CASE : Optional[int] ={ '''google/pegasus-xsum''': 512, } __SCREAMING_SNAKE_CASE : Tuple =logging.get_logger(__name__) class A_ ( __a ): _A :List[str] = VOCAB_FILES_NAMES _A :Tuple = VOCAB_FILES_NAMES _A :Any = PRETRAINED_VOCAB_FILES_MAP _A :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A :Dict = ['''input_ids''', '''attention_mask'''] def __init__( self : str , snake_case__ : int , snake_case__ : str="<pad>" , snake_case__ : str="</s>" , snake_case__ : Dict="<unk>" , snake_case__ : int="<mask_2>" , snake_case__ : Union[str, Any]="<mask_1>" , snake_case__ : str=None , snake_case__ : List[str]=1_03 , snake_case__ : Optional[Dict[str, Any]] = None , **snake_case__ : List[str] , ): lowercase = offset if additional_special_tokens is not None: if not isinstance(snake_case__ , snake_case__ ): raise TypeError( F"""additional_special_tokens should be of type {type(snake_case__ )}, but is""" F""" {type(snake_case__ )}""" ) lowercase = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F"""<unk_{i}>""" for i in range(len(snake_case__ ) , self.offset - 1 ) ] if len(set(snake_case__ ) ) != len(snake_case__ ): raise ValueError( """Please make sure that the provided additional_special_tokens do not contain an incorrectly""" F""" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.""" ) lowercase = additional_special_tokens_extended else: lowercase = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset )] lowercase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case__ , unk_token=snake_case__ , mask_token=snake_case__ , pad_token=snake_case__ , mask_token_sent=snake_case__ , offset=snake_case__ , additional_special_tokens=snake_case__ , sp_model_kwargs=self.sp_model_kwargs , **snake_case__ , ) lowercase = mask_token_sent lowercase = vocab_file lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case__ ) # add special tokens to encoder dict lowercase = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) lowercase = {v: k for k, v in self.encoder.items()} @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): return len(self.sp_model ) + self.offset def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): lowercase = {self.convert_ids_to_tokens(snake_case__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): lowercase = self.__dict__.copy() lowercase = None return state def __setstate__( self : List[Any] , snake_case__ : Dict ): lowercase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowercase = {} lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case__ : str ): return self.sp_model.encode(snake_case__ , out_type=snake_case__ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case__ : str ): if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] lowercase = self.sp_model.piece_to_id(snake_case__ ) return sp_id + self.offset def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case__ : int ): if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: lowercase = self.sp_model.IdToPiece(index - self.offset ) return token def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , snake_case__ : Optional[int] ): lowercase = [] lowercase = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(snake_case__ ) + token lowercase = [] else: current_sub_tokens.append(snake_case__ ) out_string += self.sp_model.decode(snake_case__ ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self : int , snake_case__ : str=False ): return 1 def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case__ : Optional[int] ): lowercase = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def SCREAMING_SNAKE_CASE__ ( self : str , snake_case__ : List , snake_case__ : Optional[List] = None , snake_case__ : bool = False ): if already_has_special_tokens: return self._special_token_mask(snake_case__ ) elif token_ids_a is None: return self._special_token_mask(snake_case__ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case__ : int , snake_case__ : str=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case__ : str , snake_case__ : Optional[str] = None ): if not os.path.isdir(snake_case__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase = 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__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case__ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case__ , """wb""" ) as fi: lowercase = self.sp_model.serialized_model_proto() fi.write(snake_case__ ) return (out_vocab_file,)
714
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): for param, grad_param in zip(model_a.parameters() ,model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad ,grad_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad ,grad_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})""" def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=True ): model.train() lowercase = model(lowerCAmelCase__ ) lowercase = F.mse_loss(lowerCAmelCase__ ,target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__=False ): set_seed(42 ) lowercase = RegressionModel() lowercase = deepcopy(lowerCAmelCase__ ) lowercase = RegressionDataset(length=80 ) lowercase = DataLoader(lowerCAmelCase__ ,batch_size=16 ) model.to(accelerator.device ) if sched: lowercase = AdamW(params=model.parameters() ,lr=1E-3 ) lowercase = AdamW(params=ddp_model.parameters() ,lr=1E-3 ) lowercase = LambdaLR(lowerCAmelCase__ ,lr_lambda=lambda lowerCAmelCase__ : epoch**0.65 ) lowercase = LambdaLR(lowerCAmelCase__ ,lr_lambda=lambda lowerCAmelCase__ : epoch**0.65 ) # Make a copy of `model` if sched: lowercase , lowercase , lowercase , lowercase = accelerator.prepare(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: lowercase , lowercase = accelerator.prepare(lowerCAmelCase__ ,lowerCAmelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def UpperCamelCase__ ( lowerCAmelCase__ ): # Test when on a single CPU or GPU that the context manager does nothing lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ) # Use a single batch lowercase , lowercase = next(iter(lowerCAmelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: # Sync grads step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) for param, ddp_param in zip(model.parameters() ,ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad ,ddp_param.grad ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) lowercase = ddp_input[torch.randperm(len(lowerCAmelCase__ ) )] def UpperCamelCase__ ( lowerCAmelCase__ ): # Test on distributed setup that context manager behaves properly lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ) # Use a single batch lowercase , lowercase = next(iter(lowerCAmelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: # Sync grads step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() ,ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is False ), f"""Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is True ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) lowercase = ddp_input[torch.randperm(len(lowerCAmelCase__ ) )] def UpperCamelCase__ ( lowerCAmelCase__=False ,lowerCAmelCase__=False ): lowercase = Accelerator( split_batches=lowerCAmelCase__ ,dispatch_batches=lowerCAmelCase__ ,gradient_accumulation_steps=2 ) # Test that context manager behaves properly lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ) for iteration, batch in enumerate(lowerCAmelCase__ ): lowercase , lowercase = batch.values() # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() ,ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(lowerCAmelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" else: # Grads should not be in sync assert ( torch.allclose(param.grad ,ddp_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) lowercase = ddp_input[torch.randperm(len(lowerCAmelCase__ ) )] GradientState._reset_state() def UpperCamelCase__ ( lowerCAmelCase__=False ,lowerCAmelCase__=False ): lowercase = Accelerator( split_batches=lowerCAmelCase__ ,dispatch_batches=lowerCAmelCase__ ,gradient_accumulation_steps=2 ) # Test that context manager behaves properly lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase = get_training_setup(lowerCAmelCase__ ,lowerCAmelCase__ ) for iteration, batch in enumerate(lowerCAmelCase__ ): lowercase , lowercase = batch.values() # Gather the distributed inputs and targs for the base model lowercase , lowercase = accelerator.gather((ddp_input, ddp_target) ) lowercase , lowercase = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(lowerCAmelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(lowerCAmelCase__ ): step_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f"""Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n""" lowercase = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(lowerCAmelCase__ )) if accelerator.num_processes > 1: check_model_parameters(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def UpperCamelCase__ ( ): lowercase = Accelerator() lowercase = RegressionDataset(length=80 ) lowercase = DataLoader(lowerCAmelCase__ ,batch_size=16 ) lowercase = RegressionDataset(length=96 ) lowercase = DataLoader(lowerCAmelCase__ ,batch_size=16 ) lowercase , lowercase = accelerator.prepare(lowerCAmelCase__ ,lowerCAmelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(lowerCAmelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowerCAmelCase__ ) if iteration < len(lowerCAmelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(lowerCAmelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(lowerCAmelCase__ ) if batch_num < len(lowerCAmelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def UpperCamelCase__ ( ): lowercase = Accelerator() lowercase = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(lowerCAmelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(lowerCAmelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ ,f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" ,) test_gradient_accumulation(lowerCAmelCase__ ,lowerCAmelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" ,"""2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ ,"""`split_batches=False`, `dispatch_batches=False`**""" ,) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ ,f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""" ,) test_gradient_accumulation_with_opt_and_scheduler(lowerCAmelCase__ ,lowerCAmelCase__ ) def UpperCamelCase__ ( lowerCAmelCase__ ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
72
0
from math import ceil, sqrt def __lowerCamelCase ( lowerCamelCase__ = 1_000_000 ): """simple docstring""" lowercase__ : Dict = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowercase__ : Tuple = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowercase__ : int = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'''{solution() = }''')
496
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class lowercase_ ( unittest.TestCase): """simple docstring""" def lowercase__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowercase__ ( self ): """simple docstring""" a_ = 1 a_ = 3 a_ = (32, 32) a_ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_UpperCAmelCase ) return image @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) a_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) return model @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) a_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def lowercase__ ( self ): """simple docstring""" torch.manual_seed(0 ) a_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(_UpperCAmelCase ) @property def lowercase__ ( self ): """simple docstring""" def extract(*_UpperCAmelCase , **_UpperCAmelCase ): class lowercase_ : """simple docstring""" def __init__( self ): """simple docstring""" a_ = torch.ones([0] ) def lowercase__ ( self , _UpperCAmelCase ): """simple docstring""" self.pixel_values.to(_UpperCAmelCase ) return self return Out() return extract def lowercase__ ( self ): """simple docstring""" a_ = """cpu""" # ensure determinism for the device-dependent torch.Generator a_ = self.dummy_cond_unet a_ = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=_UpperCAmelCase , set_alpha_to_one=_UpperCAmelCase , ) a_ = self.dummy_vae a_ = self.dummy_text_encoder a_ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk a_ = StableDiffusionPipeline( unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=self.dummy_extractor , ) a_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) a_ = """A painting of a squirrel eating a burger""" a_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) a_ = sd_pipe([prompt] , generator=_UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) a_ = output.images a_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=_UpperCAmelCase , )[0] a_ = image[0, -3:, -3:, -1] a_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a_ = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" a_ = """cpu""" # ensure determinism for the device-dependent torch.Generator a_ = self.dummy_cond_unet a_ = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) a_ = self.dummy_vae a_ = self.dummy_text_encoder a_ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk a_ = StableDiffusionPipeline( unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=self.dummy_extractor , ) a_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) a_ = """A painting of a squirrel eating a burger""" a_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) a_ = sd_pipe([prompt] , generator=_UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) a_ = output.images a_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=_UpperCAmelCase , )[0] a_ = image[0, -3:, -3:, -1] a_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a_ = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" a_ = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=_UpperCAmelCase ) assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) assert isinstance(pipe.scheduler , _UpperCAmelCase ) assert pipe.safety_checker is None a_ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_UpperCAmelCase ) a_ = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ) # sanity check that the pipeline still works assert pipe.safety_checker is None a_ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def lowercase__ ( self ): """simple docstring""" a_ = self.dummy_cond_unet a_ = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) a_ = self.dummy_vae a_ = self.dummy_text_encoder a_ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 a_ = unet.half() a_ = vae.half() a_ = bert.half() # make sure here that pndm scheduler skips prk a_ = StableDiffusionPipeline( unet=_UpperCAmelCase , scheduler=_UpperCAmelCase , vae=_UpperCAmelCase , text_encoder=_UpperCAmelCase , tokenizer=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=self.dummy_extractor , ) a_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) a_ = """A painting of a squirrel eating a burger""" a_ = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class lowercase_ ( unittest.TestCase): """simple docstring""" def lowercase__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self ): """simple docstring""" a_ = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=_UpperCAmelCase ) a_ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) a_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) a_ = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) a_ = 4_003_660_346 a_ = 7 # without safety guidance (sld_guidance_scale = 0) a_ = torch.manual_seed(_UpperCAmelCase ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) a_ = output.images a_ = image[0, -3:, -3:, -1] a_ = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) a_ = torch.manual_seed(_UpperCAmelCase ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) a_ = output.images a_ = image[0, -3:, -3:, -1] a_ = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" a_ = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=_UpperCAmelCase ) a_ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) a_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) a_ = """padme amidala taking a bath artwork, safe for work, no nudity""" a_ = 2_734_971_755 a_ = 7 a_ = torch.manual_seed(_UpperCAmelCase ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) a_ = output.images a_ = image[0, -3:, -3:, -1] a_ = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 a_ = torch.manual_seed(_UpperCAmelCase ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) a_ = output.images a_ = image[0, -3:, -3:, -1] a_ = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase__ ( self ): """simple docstring""" a_ = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) a_ = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) a_ = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) a_ = 1_044_355_234 a_ = 12 a_ = torch.manual_seed(_UpperCAmelCase ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) a_ = output.images a_ = image[0, -3:, -3:, -1] a_ = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 a_ = torch.manual_seed(_UpperCAmelCase ) a_ = sd_pipe( [prompt] , generator=_UpperCAmelCase , guidance_scale=_UpperCAmelCase , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2_000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) a_ = output.images a_ = image[0, -3:, -3:, -1] a_ = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
483
0
"""simple docstring""" from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean A__ : Dict = 0 A__ : int = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] A__ : str = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right A__ : Any = tuple[int, int] class _lowercase : '''simple docstring''' def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , )-> None: UpperCAmelCase__ : Tuple = pos_x UpperCAmelCase__ : List[str] = pos_y UpperCAmelCase__ : List[Any] = (pos_y, pos_x) UpperCAmelCase__ : List[Any] = goal_x UpperCAmelCase__ : Any = goal_y UpperCAmelCase__ : str = g_cost UpperCAmelCase__ : int = parent UpperCAmelCase__ : List[str] = self.calculate_heuristic() UpperCAmelCase__ : Optional[Any] = self.g_cost + self.h_cost def lowerCAmelCase__ ( self )-> float: UpperCAmelCase__ : Union[str, Any] = self.pos_x - self.goal_x UpperCAmelCase__ : str = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(__UpperCamelCase ) + abs(__UpperCamelCase ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self , __UpperCamelCase )-> bool: return self.f_cost < other.f_cost class _lowercase : '''simple docstring''' def __init__( self , __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCAmelCase__ : Tuple = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __UpperCamelCase ) UpperCAmelCase__ : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , __UpperCamelCase ) UpperCAmelCase__ : int = [self.start] UpperCAmelCase__ : list[Node] = [] UpperCAmelCase__ : Dict = False def lowerCAmelCase__ ( self )-> list[TPosition]: while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() UpperCAmelCase__ : List[Any] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(__UpperCamelCase ) self.closed_nodes.append(__UpperCamelCase ) UpperCAmelCase__ : str = self.get_successors(__UpperCamelCase ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(__UpperCamelCase ) else: # retrieve the best current path UpperCAmelCase__ : Any = self.open_nodes.pop(self.open_nodes.index(__UpperCamelCase ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(__UpperCamelCase ) else: self.open_nodes.append(__UpperCamelCase ) return [self.start.pos] def lowerCAmelCase__ ( self , __UpperCamelCase )-> list[Node]: UpperCAmelCase__ : str = [] for action in delta: UpperCAmelCase__ : Dict = parent.pos_x + action[1] UpperCAmelCase__ : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__UpperCamelCase ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( __UpperCamelCase , __UpperCamelCase , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __UpperCamelCase , ) ) return successors def lowerCAmelCase__ ( self , __UpperCamelCase )-> list[TPosition]: UpperCAmelCase__ : Optional[int] = node UpperCAmelCase__ : List[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCAmelCase__ : Tuple = current_node.parent path.reverse() return path class _lowercase : '''simple docstring''' def __init__( self , __UpperCamelCase , __UpperCamelCase )-> None: UpperCAmelCase__ : Any = AStar(__UpperCamelCase , __UpperCamelCase ) UpperCAmelCase__ : Optional[int] = AStar(__UpperCamelCase , __UpperCamelCase ) UpperCAmelCase__ : int = False def lowerCAmelCase__ ( self )-> list[TPosition]: while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() UpperCAmelCase__ : int = self.fwd_astar.open_nodes.pop(0 ) UpperCAmelCase__ : Dict = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( __UpperCamelCase , __UpperCamelCase ) self.fwd_astar.closed_nodes.append(__UpperCamelCase ) self.bwd_astar.closed_nodes.append(__UpperCamelCase ) UpperCAmelCase__ : List[str] = current_bwd_node UpperCAmelCase__ : Any = current_fwd_node UpperCAmelCase__ : List[str] = { self.fwd_astar: self.fwd_astar.get_successors(__UpperCamelCase ), self.bwd_astar: self.bwd_astar.get_successors(__UpperCamelCase ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(__UpperCamelCase ) else: # retrieve the best current path UpperCAmelCase__ : Any = astar.open_nodes.pop( astar.open_nodes.index(__UpperCamelCase ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(__UpperCamelCase ) else: astar.open_nodes.append(__UpperCamelCase ) return [self.fwd_astar.start.pos] def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase )-> list[TPosition]: UpperCAmelCase__ : Tuple = self.fwd_astar.retrace_path(__UpperCamelCase ) UpperCAmelCase__ : Tuple = self.bwd_astar.retrace_path(__UpperCamelCase ) bwd_path.pop() bwd_path.reverse() UpperCAmelCase__ : Any = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] A__ : Any = (0, 0) A__ : Tuple = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) A__ : Any = time.time() A__ : int = AStar(init, goal) A__ : List[Any] = a_star.search() A__ : Optional[int] = time.time() - start_time print(f"""AStar execution time = {end_time:f} seconds""") A__ : List[Any] = time.time() A__ : int = BidirectionalAStar(init, goal) A__ : Any = time.time() - bd_start_time print(f"""BidirectionalAStar execution time = {bd_end_time:f} seconds""")
660
"""simple docstring""" import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging A__ : Tuple = logging.get_logger(__name__) def a__ ( lowerCAmelCase : nn.ModuleList , lowerCAmelCase : nn.ModuleList , lowerCAmelCase : List[int] ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ), F"{len(lowerCAmelCase )} != {len(lowerCAmelCase )}" dest_layers.load_state_dict(layers_to_copy.state_dict() ) A__ : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } A__ : List[Any] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def a__ ( lowerCAmelCase : Dict , lowerCAmelCase : Dict ): '''simple docstring''' try: UpperCAmelCase__ : Tuple = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first" F" {n_student}" ) return list(range(lowerCAmelCase ) ) def a__ ( lowerCAmelCase : int , lowerCAmelCase : Tuple ): '''simple docstring''' if n_student > n_teacher: raise ValueError(F"Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}" ) elif n_teacher == n_student: return list(range(lowerCAmelCase ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def a__ ( lowerCAmelCase : Union[str, PreTrainedModel] , lowerCAmelCase : Union[str, Path] = "student" , lowerCAmelCase : Union[int, None] = None , lowerCAmelCase : Union[int, None] = None , lowerCAmelCase : List[str]=False , lowerCAmelCase : List[str]=None , lowerCAmelCase : List[str]=None , **lowerCAmelCase : List[str] , ): '''simple docstring''' UpperCAmelCase__ : List[str] = "encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher." assert (e is not None) or (d is not None), _msg if isinstance(lowerCAmelCase , lowerCAmelCase ): AutoTokenizer.from_pretrained(lowerCAmelCase ).save_pretrained(lowerCAmelCase ) # purely for convenience UpperCAmelCase__ : List[str] = AutoModelForSeqaSeqLM.from_pretrained(lowerCAmelCase ).eval() else: assert isinstance(lowerCAmelCase , lowerCAmelCase ), F"teacher must be a model or string got type {type(lowerCAmelCase )}" UpperCAmelCase__ : int = teacher.config.to_diff_dict() try: UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: UpperCAmelCase__ : Tuple = teacher_e if d is None: UpperCAmelCase__ : str = teacher_d init_kwargs.update({"encoder_layers": e, "decoder_layers": d} ) except AttributeError: # T5 if hasattr(teacher.config , "num_encoder_layers" ): UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: UpperCAmelCase__ : Optional[Any] = teacher_e if d is None: UpperCAmelCase__ : Optional[Any] = teacher_d if hasattr(teacher.config , "num_encoder_layers" ): init_kwargs.update({"num_encoder_layers": e, "num_decoder_layers": d} ) else: init_kwargs.update({"num_layers": e, "num_decoder_layers": d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(lowerCAmelCase ) # Copy weights UpperCAmelCase__ : Tuple = teacher.config_class(**lowerCAmelCase ) UpperCAmelCase__ : List[str] = AutoModelForSeqaSeqLM.from_config(lowerCAmelCase ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. UpperCAmelCase__ : Optional[int] = student.load_state_dict(teacher.state_dict() , strict=lowerCAmelCase ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save UpperCAmelCase__ , UpperCAmelCase__ : int = list(range(lowerCAmelCase ) ), list(range(lowerCAmelCase ) ) logger.info( F"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to" F" {save_path}" ) student.save_pretrained(lowerCAmelCase ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: UpperCAmelCase__ : List[int] = pick_layers_to_copy(lowerCAmelCase , lowerCAmelCase ) if d_layers_to_copy is None: UpperCAmelCase__ : List[int] = pick_layers_to_copy(lowerCAmelCase , lowerCAmelCase ) try: if hasattr( lowerCAmelCase , "prophetnet" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , lowerCAmelCase ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , lowerCAmelCase ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , lowerCAmelCase ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , lowerCAmelCase ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , lowerCAmelCase ) copy_layers(teacher.decoder.block , student.decoder.block , lowerCAmelCase ) logger.info( F"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}" ) UpperCAmelCase__ : int = { "teacher_type": teacher.config.model_type, "copied_encoder_layers": e_layers_to_copy, "copied_decoder_layers": d_layers_to_copy, } student.save_pretrained(lowerCAmelCase ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
660
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class UpperCAmelCase__ ( __lowerCamelCase ): """simple docstring""" lowerCAmelCase__ : Union[str, Any] = """big_bird""" def __init__( self , _SCREAMING_SNAKE_CASE=5_0_3_5_8 , _SCREAMING_SNAKE_CASE=7_6_8 , _SCREAMING_SNAKE_CASE=1_2 , _SCREAMING_SNAKE_CASE=1_2 , _SCREAMING_SNAKE_CASE=3_0_7_2 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=4_0_9_6 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=6_6 , _SCREAMING_SNAKE_CASE="block_sparse" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=6_4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> str: super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , sep_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) a_ : Tuple = vocab_size a_ : Optional[int] = max_position_embeddings a_ : Optional[int] = hidden_size a_ : Tuple = num_hidden_layers a_ : Dict = num_attention_heads a_ : Union[str, Any] = intermediate_size a_ : Union[str, Any] = hidden_act a_ : Tuple = hidden_dropout_prob a_ : Optional[int] = attention_probs_dropout_prob a_ : Union[str, Any] = initializer_range a_ : Union[str, Any] = type_vocab_size a_ : Union[str, Any] = layer_norm_eps a_ : Optional[int] = use_cache a_ : Tuple = rescale_embeddings a_ : Dict = attention_type a_ : Union[str, Any] = use_bias a_ : Optional[Any] = block_size a_ : Dict = num_random_blocks a_ : Union[str, Any] = classifier_dropout class UpperCAmelCase__ ( __lowerCamelCase ): """simple docstring""" @property def A ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: a_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
473
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ (_SCREAMING_SNAKE_CASE :tuple[int, int] , _SCREAMING_SNAKE_CASE :int ) -> list[tuple[int, int]]: a_ , a_ : Optional[int] = position a_ : Optional[Any] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] a_ : List[str] = [] for position in positions: a_ , a_ : List[Any] = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(_SCREAMING_SNAKE_CASE ) return permissible_positions def lowerCAmelCase_ (_SCREAMING_SNAKE_CASE :list[list[int]] ) -> bool: return not any(elem == 0 for row in board for elem in row ) def lowerCAmelCase_ (_SCREAMING_SNAKE_CASE :list[list[int]] , _SCREAMING_SNAKE_CASE :tuple[int, int] , _SCREAMING_SNAKE_CASE :int ) -> bool: if is_complete(_SCREAMING_SNAKE_CASE ): return True for position in get_valid_pos(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ): a_ , a_ : int = position if board[y][x] == 0: a_ : Any = curr + 1 if open_knight_tour_helper(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , curr + 1 ): return True a_ : Optional[Any] = 0 return False def lowerCAmelCase_ (_SCREAMING_SNAKE_CASE :int ) -> list[list[int]]: a_ : int = [[0 for i in range(_SCREAMING_SNAKE_CASE )] for j in range(_SCREAMING_SNAKE_CASE )] for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): a_ : Optional[int] = 1 if open_knight_tour_helper(_SCREAMING_SNAKE_CASE , (i, j) , 1 ): return board a_ : Dict = 0 a_ : Union[str, Any] = F'''Open Kight Tour cannot be performed on a board of size {n}''' raise ValueError(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
473
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __lowercase = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PerceiverConfig''', '''PerceiverOnnxConfig'''], '''tokenization_perceiver''': ['''PerceiverTokenizer'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''PerceiverFeatureExtractor'''] __lowercase = ['''PerceiverImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PerceiverForImageClassificationConvProcessing''', '''PerceiverForImageClassificationFourier''', '''PerceiverForImageClassificationLearned''', '''PerceiverForMaskedLM''', '''PerceiverForMultimodalAutoencoding''', '''PerceiverForOpticalFlow''', '''PerceiverForSequenceClassification''', '''PerceiverLayer''', '''PerceiverModel''', '''PerceiverPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
305
'''simple docstring''' import json import os import shutil 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 AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 __lowercase = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 1_28, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class _snake_case ( unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : List[str] ): lowerCAmelCase_ : str =TOKEN HfFolder.save_token(UpperCamelCase_ ) @classmethod def __A ( cls : Union[str, Any] ): try: delete_repo(token=cls._token , repo_id='''test-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-config-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-config''' ) except HTTPError: pass def __A ( self : Dict ): lowerCAmelCase_ : List[Any] =BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''test-config''' , use_auth_token=self._token ) lowerCAmelCase_ : List[str] =BertConfig.from_pretrained(F'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCamelCase_ , repo_id='''test-config''' , push_to_hub=UpperCamelCase_ , use_auth_token=self._token ) lowerCAmelCase_ : List[Any] =BertConfig.from_pretrained(F'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) def __A ( self : Tuple ): lowerCAmelCase_ : Optional[int] =BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('''valid_org/test-config-org''' , use_auth_token=self._token ) lowerCAmelCase_ : Union[str, Any] =BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCamelCase_ , repo_id='''valid_org/test-config-org''' , push_to_hub=UpperCamelCase_ , use_auth_token=self._token ) lowerCAmelCase_ : int =BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) def __A ( self : str ): CustomConfig.register_for_auto_class() lowerCAmelCase_ : List[str] =CustomConfig(attribute=42 ) config.push_to_hub('''test-dynamic-config''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'''AutoConfig''': '''custom_configuration.CustomConfig'''} ) lowerCAmelCase_ : Optional[int] =AutoConfig.from_pretrained(F'{USER}/test-dynamic-config' , trust_remote_code=UpperCamelCase_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , '''CustomConfig''' ) self.assertEqual(new_config.attribute , 42 ) class _snake_case ( unittest.TestCase ): """simple docstring""" def __A ( self : Dict ): lowerCAmelCase_ : int =GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated lowerCAmelCase_ : str =c.n_embd + 1 # int lowerCAmelCase_ : Tuple =c.resid_pdrop + 1.0 # float lowerCAmelCase_ : Optional[Any] =not c.scale_attn_weights # bool lowerCAmelCase_ : Union[str, Any] =c.summary_type + '''foo''' # str c.update_from_string( F'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(UpperCamelCase_ , c.n_embd , '''mismatch for key: n_embd''' ) self.assertEqual(UpperCamelCase_ , c.resid_pdrop , '''mismatch for key: resid_pdrop''' ) self.assertEqual(UpperCamelCase_ , c.scale_attn_weights , '''mismatch for key: scale_attn_weights''' ) self.assertEqual(UpperCamelCase_ , c.summary_type , '''mismatch for key: summary_type''' ) def __A ( self : Union[str, Any] ): lowerCAmelCase_ : Union[str, Any] =PretrainedConfig() lowerCAmelCase_ : Dict =[key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( UpperCamelCase_ , ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version'''] ) lowerCAmelCase_ : Tuple =[key for key, value in config_common_kwargs.items() if value == getattr(UpperCamelCase_ , UpperCamelCase_ )] if len(UpperCamelCase_ ) > 0: raise ValueError( '''The following keys are set with the default values in''' ''' `test_configuration_common.config_common_kwargs` pick another value for them:''' F' {", ".join(UpperCamelCase_ )}.' ) def __A ( self : Optional[int] ): with self.assertRaises(UpperCamelCase_ ): # config is in subfolder, the following should not work without specifying the subfolder lowerCAmelCase_ : str =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' ) lowerCAmelCase_ : int =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' , subfolder='''bert''' ) self.assertIsNotNone(UpperCamelCase_ ) def __A ( self : List[Any] ): # A mock response for an HTTP head request to emulate server down lowerCAmelCase_ : List[str] =mock.Mock() lowerCAmelCase_ : List[str] =500 lowerCAmelCase_ : Tuple ={} lowerCAmelCase_ : Union[str, Any] =HTTPError lowerCAmelCase_ : Dict ={} # Download this model to make sure it's in the cache. lowerCAmelCase_ : Dict =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=UpperCamelCase_ ) as mock_head: lowerCAmelCase_ : List[str] =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Dict ): # This test is for deprecated behavior and can be removed in v5 lowerCAmelCase_ : Union[str, Any] =BertConfig.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''' ) def __A ( self : int ): lowerCAmelCase_ : Union[str, Any] =AutoConfig.from_pretrained('''bert-base-cased''' ) lowerCAmelCase_ : Tuple =['''config.4.0.0.json'''] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(UpperCamelCase_ ) lowerCAmelCase_ : str =2 json.dump(configuration.to_dict() , open(os.path.join(UpperCamelCase_ , '''config.4.0.0.json''' ) , '''w''' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 lowerCAmelCase_ : Optional[Any] =AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 lowerCAmelCase_ : List[Any] =['''config.42.0.0.json'''] lowerCAmelCase_ : Optional[int] =768 configuration.save_pretrained(UpperCamelCase_ ) shutil.move(os.path.join(UpperCamelCase_ , '''config.4.0.0.json''' ) , os.path.join(UpperCamelCase_ , '''config.42.0.0.json''' ) ) lowerCAmelCase_ : int =AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertEqual(new_configuration.hidden_size , 768 ) def __A ( self : int ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. lowerCAmelCase_ : Dict ='''hf-internal-testing/test-two-configs''' import transformers as new_transformers lowerCAmelCase_ : Tuple ='''v4.0.0''' lowerCAmelCase_ , lowerCAmelCase_ : int =new_transformers.models.auto.AutoConfig.from_pretrained( UpperCamelCase_ , return_unused_kwargs=UpperCamelCase_ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(UpperCamelCase_ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers lowerCAmelCase_ : Optional[Any] ='''v3.0.0''' lowerCAmelCase_ : List[Any] =old_transformers.models.auto.AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertEqual(old_configuration.hidden_size , 768 )
305
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case_ ( lowerCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = KandinskyVaaImgaImgPipeline snake_case__ = ['image_embeds', 'negative_image_embeds', 'image'] snake_case__ = [ 'image_embeds', 'negative_image_embeds', 'image', ] snake_case__ = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] snake_case__ = False @property def UpperCAmelCase__ (self: int ) -> int: '''simple docstring''' return 32 @property def UpperCAmelCase__ (self: Optional[Any] ) -> Optional[Any]: '''simple docstring''' return 32 @property def UpperCAmelCase__ (self: Optional[int] ) -> str: '''simple docstring''' return self.time_input_dim @property def UpperCAmelCase__ (self: Tuple ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def UpperCAmelCase__ (self: Dict ) -> Dict: '''simple docstring''' return 100 @property def UpperCAmelCase__ (self: List[Any] ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) __a : Any = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } __a : List[str] = UNetaDConditionModel(**lowercase__ ) return model @property def UpperCAmelCase__ (self: Dict ) -> Tuple: '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCAmelCase__ (self: List[Any] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __a : int = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase__ (self: str ) -> List[str]: '''simple docstring''' __a : List[str] = self.dummy_unet __a : Optional[Any] = self.dummy_movq __a : Optional[int] = { "num_train_timesteps": 1000, "beta_schedule": "linear", "beta_start": 0.0_00_85, "beta_end": 0.0_12, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } __a : Union[str, Any] = DDIMScheduler(**lowercase__ ) __a : Any = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def UpperCAmelCase__ (self: Union[str, Any] , __UpperCAmelCase: str , __UpperCAmelCase: List[str]=0 ) -> str: '''simple docstring''' __a : int = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) __a : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( lowercase__ ) # create init_image __a : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) __a : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Union[str, Any] = Image.fromarray(np.uinta(lowercase__ ) ).convert("RGB" ).resize((256, 256) ) if str(lowercase__ ).startswith("mps" ): __a : Optional[int] = torch.manual_seed(lowercase__ ) else: __a : Dict = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) __a : int = { "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 10, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def UpperCAmelCase__ (self: Union[str, Any] ) -> Any: '''simple docstring''' __a : int = "cpu" __a : Tuple = self.get_dummy_components() __a : Optional[Any] = self.pipeline_class(**lowercase__ ) __a : Union[str, Any] = pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) __a : Any = pipe(**self.get_dummy_inputs(lowercase__ ) ) __a : Dict = output.images __a : str = pipe( **self.get_dummy_inputs(lowercase__ ) , return_dict=lowercase__ , )[0] __a : List[Any] = image[0, -3:, -3:, -1] __a : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __a : Union[str, Any] = np.array( [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class snake_case_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ (self: Dict ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ (self: List[Any] ) -> Optional[Any]: '''simple docstring''' __a : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_img2img_frog.npy" ) __a : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __a : str = "A red cartoon frog, 4k" __a : List[Any] = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(lowercase__ ) __a : str = KandinskyVaaImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) __a : Union[str, Any] = pipeline.to(lowercase__ ) pipeline.set_progress_bar_config(disable=lowercase__ ) __a : Tuple = torch.Generator(device="cpu" ).manual_seed(0 ) __a , __a : Union[str, Any] = pipe_prior( lowercase__ , generator=lowercase__ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __a : Any = pipeline( image=lowercase__ , image_embeds=lowercase__ , negative_image_embeds=lowercase__ , generator=lowercase__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="np" , ) __a : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ )
351
'''simple docstring''' import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class lowercase_ : """simple docstring""" def __init__( self : Dict ,lowercase__ : Dict ,lowercase__ : int=1_3 ,lowercase__ : List[str]=7 ,lowercase__ : int=True ,lowercase__ : int=True ,lowercase__ : Union[str, Any]=True ,lowercase__ : List[Any]=True ,lowercase__ : str=9_9 ,lowercase__ : Optional[Any]=3_2 ,lowercase__ : Union[str, Any]=5 ,lowercase__ : List[Any]=4 ,lowercase__ : str=3_7 ,lowercase__ : Tuple="gelu" ,lowercase__ : List[Any]=0.1 ,lowercase__ : Dict=0.1 ,lowercase__ : int=1_2_8 ,lowercase__ : Dict=3_2 ,lowercase__ : Dict=1_6 ,lowercase__ : Any=2 ,lowercase__ : int=0.0_2 ,lowercase__ : List[str]=3 ,lowercase__ : Dict=4 ,lowercase__ : Optional[int]=None ,): __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_input_mask __lowercase = use_token_type_ids __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = num_labels __lowercase = num_choices __lowercase = scope def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __lowercase = None if self.use_input_mask: __lowercase = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase = None if self.use_token_type_ids: __lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) __lowercase = None __lowercase = None __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) __lowercase = ids_tensor([self.batch_size] ,self.num_choices ) __lowercase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): return NezhaConfig( 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=lowercase__ ,initializer_range=self.initializer_range ,) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.prepare_config_and_inputs() __lowercase = True __lowercase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowercase = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Union[str, Any] ,lowercase__ : List[str] ,lowercase__ : List[str] ,lowercase__ : List[str] ,lowercase__ : Tuple ,lowercase__ : Tuple ,lowercase__ : str ): __lowercase = NezhaModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ) __lowercase = model(lowercase__ ,token_type_ids=lowercase__ ) __lowercase = model(lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Dict ,lowercase__ : str ,lowercase__ : Optional[Any] ,lowercase__ : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Tuple ,lowercase__ : Tuple ,lowercase__ : Optional[int] ,lowercase__ : List[Any] ,): __lowercase = True __lowercase = NezhaModel(lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,encoder_hidden_states=lowercase__ ,encoder_attention_mask=lowercase__ ,) __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,encoder_hidden_states=lowercase__ ,) __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Tuple ,lowercase__ : Optional[Any] ,lowercase__ : List[Any] ,lowercase__ : List[Any] ,lowercase__ : Optional[Any] ): __lowercase = NezhaForMaskedLM(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Any ,lowercase__ : int ,lowercase__ : Union[str, Any] ,lowercase__ : Optional[int] ,lowercase__ : Any ): __lowercase = NezhaForNextSentencePrediction(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : str ,lowercase__ : Dict ,lowercase__ : Tuple ,lowercase__ : Dict ,lowercase__ : Tuple ,lowercase__ : int ,lowercase__ : int ): __lowercase = NezhaForPreTraining(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ,next_sentence_label=lowercase__ ,) self.parent.assertEqual(result.prediction_logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape ,(self.batch_size, 2) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Union[str, Any] ,lowercase__ : Optional[Any] ,lowercase__ : Tuple ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Optional[int] ,lowercase__ : Union[str, Any] ): __lowercase = NezhaForQuestionAnswering(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,start_positions=lowercase__ ,end_positions=lowercase__ ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Tuple ,lowercase__ : str ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : Any ,lowercase__ : Optional[int] ,lowercase__ : int ): __lowercase = self.num_labels __lowercase = NezhaForSequenceClassification(lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : Union[str, Any] ,lowercase__ : List[str] ,lowercase__ : int ,lowercase__ : List[Any] ,lowercase__ : List[Any] ,lowercase__ : Any ,lowercase__ : Optional[Any] ): __lowercase = self.num_labels __lowercase = NezhaForTokenClassification(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : List[Any] ,lowercase__ : List[Any] ,lowercase__ : Optional[Any] ,lowercase__ : List[str] ,lowercase__ : Dict ,lowercase__ : List[Any] ,lowercase__ : str ): __lowercase = self.num_choices __lowercase = NezhaForMultipleChoice(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __lowercase = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __lowercase = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __lowercase = model( lowercase__ ,attention_mask=lowercase__ ,token_type_ids=lowercase__ ,labels=lowercase__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = config_and_inputs __lowercase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowercase_ (lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE : Tuple = ( { 'feature-extraction': NezhaModel, 'fill-mask': NezhaForMaskedLM, 'question-answering': NezhaForQuestionAnswering, 'text-classification': NezhaForSequenceClassification, 'token-classification': NezhaForTokenClassification, 'zero-shot': NezhaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE : List[str] = True def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : List[str] ,lowercase__ : str ,lowercase__ : Any=False ): __lowercase = super()._prepare_for_class(lowercase__ ,lowercase__ ,return_labels=lowercase__ ) if return_labels: if model_class in get_values(lowercase__ ): __lowercase = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=lowercase__ ) __lowercase = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=lowercase__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase = NezhaModelTester(self ) __lowercase = ConfigTester(self ,config_class=lowercase__ ,hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : int ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): # This regression test was failing with PyTorch < 1.3 ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __lowercase = None self.model_tester.create_and_check_model_as_decoder( lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : str ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : str ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = NezhaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __lowercase = True __lowercase = model_class(config=lowercase__ ) __lowercase = self._prepare_for_class(lowercase__ ,lowercase__ ) __lowercase = torch.jit.trace( lowercase__ ,(inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(lowercase__ ,os.path.join(lowercase__ ,'''bert.pt''' ) ) __lowercase = torch.jit.load(os.path.join(lowercase__ ,'''bert.pt''' ) ,map_location=lowercase__ ) loaded(inputs_dict['''input_ids'''].to(lowercase__ ) ,inputs_dict['''attention_mask'''].to(lowercase__ ) ) @require_torch class lowercase_ (unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = NezhaModel.from_pretrained('''sijunhe/nezha-cn-base''' ) __lowercase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __lowercase = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowercase = model(lowercase__ ,attention_mask=lowercase__ )[0] __lowercase = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape ,lowercase__ ) __lowercase = torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,lowercase__ ,atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = NezhaForMaskedLM.from_pretrained('''sijunhe/nezha-cn-base''' ) __lowercase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __lowercase = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowercase = model(lowercase__ ,attention_mask=lowercase__ )[0] __lowercase = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape ,lowercase__ ) __lowercase = torch.tensor( [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,lowercase__ ,atol=1e-4 ) )
41
0
'''simple docstring''' import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase_ : @staticmethod def _snake_case ( *_lowerCAmelCase , **_lowerCAmelCase ) -> List[Any]: pass @is_pipeline_test @require_torch @require_vision class lowerCAmelCase_ ( unittest.TestCase ): __lowerCamelCase : Optional[Any] = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: _lowerCAmelCase = pipeline("visual-question-answering" , model="hf-internal-testing/tiny-vilt-random-vqa" ) _lowerCAmelCase = [ { "image": Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "question": "How many cats are there?", }, { "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", "question": "How many cats are there?", }, ] return vqa_pipeline, examples def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: _lowerCAmelCase = vqa_pipeline(_lowerCAmelCase , top_k=1 ) self.assertEqual( _lowerCAmelCase , [ [{"score": ANY(_lowerCAmelCase ), "answer": ANY(_lowerCAmelCase )}], [{"score": ANY(_lowerCAmelCase ), "answer": ANY(_lowerCAmelCase )}], ] , ) @require_torch def _snake_case ( self ) -> Any: _lowerCAmelCase = pipeline("visual-question-answering" , model="hf-internal-testing/tiny-vilt-random-vqa" ) _lowerCAmelCase = "./tests/fixtures/tests_samples/COCO/000000039769.png" _lowerCAmelCase = "How many cats are there?" _lowerCAmelCase = vqa_pipeline(image=_lowerCAmelCase , question="How many cats are there?" , top_k=2 ) self.assertEqual( _lowerCAmelCase , [{"score": ANY(_lowerCAmelCase ), "answer": ANY(_lowerCAmelCase )}, {"score": ANY(_lowerCAmelCase ), "answer": ANY(_lowerCAmelCase )}] ) _lowerCAmelCase = vqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( _lowerCAmelCase , [{"score": ANY(_lowerCAmelCase ), "answer": ANY(_lowerCAmelCase )}, {"score": ANY(_lowerCAmelCase ), "answer": ANY(_lowerCAmelCase )}] ) @slow @require_torch def _snake_case ( self ) -> Optional[Any]: _lowerCAmelCase = pipeline("visual-question-answering" , model="dandelin/vilt-b32-finetuned-vqa" ) _lowerCAmelCase = "./tests/fixtures/tests_samples/COCO/000000039769.png" _lowerCAmelCase = "How many cats are there?" _lowerCAmelCase = vqa_pipeline(image=_lowerCAmelCase , question=_lowerCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}] ) _lowerCAmelCase = vqa_pipeline({"image": image, "question": question} , top_k=2 ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}] ) _lowerCAmelCase = vqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [[{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}]] * 2 , ) @require_tf @unittest.skip("Visual question answering not implemented in TF" ) def _snake_case ( self ) -> Tuple: pass
489
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : str = "speech_to_text_2" __lowerCamelCase : Union[str, Any] = ["past_key_values"] __lowerCamelCase : Tuple = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"} def __init__( self , _lowerCAmelCase=10000 , _lowerCAmelCase=6 , _lowerCAmelCase=2048 , _lowerCAmelCase=4 , _lowerCAmelCase=0.0 , _lowerCAmelCase=True , _lowerCAmelCase="relu" , _lowerCAmelCase=256 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.02 , _lowerCAmelCase=2 , _lowerCAmelCase=True , _lowerCAmelCase=1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=1024 , **_lowerCAmelCase , ) -> Dict: _lowerCAmelCase = vocab_size _lowerCAmelCase = d_model _lowerCAmelCase = decoder_ffn_dim _lowerCAmelCase = decoder_layers _lowerCAmelCase = decoder_attention_heads _lowerCAmelCase = dropout _lowerCAmelCase = attention_dropout _lowerCAmelCase = activation_dropout _lowerCAmelCase = activation_function _lowerCAmelCase = init_std _lowerCAmelCase = decoder_layerdrop _lowerCAmelCase = use_cache _lowerCAmelCase = decoder_layers _lowerCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True _lowerCAmelCase = max_target_positions super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , decoder_start_token_id=_lowerCAmelCase , **_lowerCAmelCase , )
489
1
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict UpperCAmelCase = namedtuple( """_TestCommandArgs""", [ """dataset""", """name""", """cache_dir""", """data_dir""", """all_configs""", """save_infos""", """ignore_verifications""", """force_redownload""", """clear_cache""", ], defaults=[None, None, None, False, False, False, False, False], ) def _snake_case ( __snake_case : int , __snake_case : str ): """simple docstring""" return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def _snake_case ( __snake_case : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = _TestCommandArgs(dataset=__snake_case , all_configs=__snake_case , save_infos=__snake_case ) _lowerCamelCase : Union[str, Any] = TestCommand(*__snake_case ) test_command.run() _lowerCamelCase : List[str] = os.path.join(__snake_case , """README.md""" ) assert os.path.exists(__snake_case ) _lowerCamelCase : Dict = DatasetInfosDict.from_directory(__snake_case ) _lowerCamelCase : int = DatasetInfosDict( { """default""": DatasetInfo( features=Features( { """tokens""": Sequence(Value("""string""" ) ), """ner_tags""": Sequence( ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ), """langs""": Sequence(Value("""string""" ) ), """spans""": Sequence(Value("""string""" ) ), } ) , splits=[ { """name""": """train""", """num_bytes""": 2351563, """num_examples""": 10000, }, { """name""": """validation""", """num_bytes""": 238418, """num_examples""": 1000, }, ] , download_size=3940680 , dataset_size=2589981 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: _lowerCamelCase , _lowerCamelCase : Any = getattr(dataset_infos["""default"""] , __snake_case ), getattr(expected_dataset_infos["""default"""] , __snake_case ) if key == "num_bytes": assert is_apercent_close(__snake_case , __snake_case ) elif key == "splits": assert list(__snake_case ) == list(__snake_case ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
88
'''simple docstring''' import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor UpperCamelCase__ : Optional[Any] = logging.getLogger(__name__) UpperCamelCase__ : Dict = 50 # max width of layer names UpperCamelCase__ : Any = 70 # max width of quantizer names def __UpperCamelCase( _A : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : List[str] = parser.add_argument_group('''quant_trainer arguments''' ) group.add_argument('''--wprec''' , type=_A , default=8 , help='''weight precision''' ) group.add_argument('''--aprec''' , type=_A , default=8 , help='''activation precision''' ) group.add_argument('''--quant-per-tensor''' , action='''store_true''' , help='''per tensor weight scaling''' ) group.add_argument('''--quant-disable''' , action='''store_true''' , help='''disable all quantizers''' ) group.add_argument('''--quant-disable-embeddings''' , action='''store_true''' , help='''disable all embeddings quantizers''' ) group.add_argument('''--quant-disable-keyword''' , type=_A , nargs='''+''' , help='''disable quantizers by keyword''' ) group.add_argument('''--quant-disable-layer-module''' , type=_A , help='''disable quantizers by keyword under layer.''' ) group.add_argument('''--quant-enable-layer-module''' , type=_A , help='''enable quantizers by keyword under layer''' ) group.add_argument('''--calibrator''' , default='''max''' , help='''which quantization range calibrator to use''' ) group.add_argument('''--percentile''' , default=_A , type=_A , help='''percentile for PercentileCalibrator''' ) group.add_argument('''--fuse-qkv''' , action='''store_true''' , help='''use the same scale factor for qkv''' ) group.add_argument('''--clip-gelu''' , metavar='''N''' , type=_A , help='''clip gelu output maximum value to N''' ) group.add_argument( '''--recalibrate-weights''' , action='''store_true''' , help=( '''recalibrate weight amaxes by taking the max of the weights.''' ''' amaxes will be computed with the current quantization granularity (axis).''' ) , ) def __UpperCamelCase( _A : Tuple ): '''simple docstring''' if args.calibrator == "max": UpperCAmelCase__ : str = '''max''' elif args.calibrator == "percentile": if args.percentile is None: raise ValueError('''Specify --percentile when using percentile calibrator''' ) UpperCAmelCase__ : Dict = '''histogram''' elif args.calibrator == "mse": UpperCAmelCase__ : Any = '''histogram''' else: raise ValueError(F'''Invalid calibrator {args.calibrator}''' ) UpperCAmelCase__ : Dict = QuantDescriptor(num_bits=args.aprec , calib_method=_A ) UpperCAmelCase__ : str = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)) ) quant_nn.QuantLinear.set_default_quant_desc_input(_A ) quant_nn.QuantLinear.set_default_quant_desc_weight(_A ) def __UpperCamelCase( _A : Any , _A : Any , _A : Any=False , _A : Optional[Any]=False ): '''simple docstring''' logger.info('''Configuring Model for Quantization''' ) logger.info(F'''using quantization package {pytorch_quantization.__file__}''' ) if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(_A , ['''embeddings'''] , which='''weight''' , _disabled=_A ) if args.quant_disable: set_quantizer_by_name(_A , [''''''] , _disabled=_A ) if args.quant_disable_keyword: set_quantizer_by_name(_A , args.quant_disable_keyword , _disabled=_A ) if args.quant_disable_layer_module: set_quantizer_by_name(_A , [R'''layer.\d+.''' + args.quant_disable_layer_module] , _disabled=_A ) if args.quant_enable_layer_module: set_quantizer_by_name(_A , [R'''layer.\d+.''' + args.quant_enable_layer_module] , _disabled=_A ) if args.recalibrate_weights: recalibrate_weights(_A ) if args.fuse_qkv: fuse_qkv(_A , _A ) if args.clip_gelu: clip_gelu(_A , args.clip_gelu ) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(_A ) def __UpperCamelCase( _A : str ): '''simple docstring''' logger.info('''Enabling Calibration''' ) for name, module in model.named_modules(): if name.endswith('''_quantizer''' ): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(F'''{name:80}: {module}''' ) def __UpperCamelCase( _A : Tuple , _A : Any ): '''simple docstring''' logger.info('''Loading calibrated amax''' ) for name, module in model.named_modules(): if name.endswith('''_quantizer''' ): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator ): module.load_calib_amax() else: module.load_calib_amax('''percentile''' , percentile=args.percentile ) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(_A ) def __UpperCamelCase( _A : Dict , _A : Optional[int] ): '''simple docstring''' def fusea(_A : Optional[Any] , _A : Optional[Any] , _A : Dict ): for mod in [qq, qk, qv]: if not hasattr(_A , '''_amax''' ): print(''' WARNING: NO AMAX BUFFER''' ) return UpperCAmelCase__ : Dict = qq._amax.detach().item() UpperCAmelCase__ : List[Any] = qk._amax.detach().item() UpperCAmelCase__ : Optional[int] = qv._amax.detach().item() UpperCAmelCase__ : Dict = max(_A , _A , _A ) qq._amax.fill_(_A ) qk._amax.fill_(_A ) qv._amax.fill_(_A ) logger.info(F''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''' ) for name, mod in model.named_modules(): if name.endswith('''.attention.self''' ): logger.info(F'''FUSE_QKV: {name:{name_width}}''' ) fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer ) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer ) def __UpperCamelCase( _A : Dict , _A : Any ): '''simple docstring''' for name, mod in model.named_modules(): if name.endswith('''.output.dense''' ) and not name.endswith('''attention.output.dense''' ): UpperCAmelCase__ : Union[str, Any] = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=_A ) UpperCAmelCase__ : Tuple = mod._input_quantizer._amax.data.detach().item() logger.info(F'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''' ) def __UpperCamelCase( _A : str ): '''simple docstring''' for name, mod in model.named_modules(): if hasattr(_A , '''_weight_quantizer''' ) and mod._weight_quantizer.axis is not None: UpperCAmelCase__ : int = mod.weight.shape[0] UpperCAmelCase__ : Tuple = mod._weight_quantizer._amax.detach() UpperCAmelCase__ : Optional[int] = torch.ones(_A , dtype=amax.dtype , device=amax.device ) * amax print(F'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''' ) def __UpperCamelCase( _A : List[str] ): '''simple docstring''' for name, mod in model.named_modules(): if hasattr(_A , '''_weight_quantizer''' ): if not hasattr(mod.weight_quantizer , '''_amax''' ): print('''RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER''' ) continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) UpperCAmelCase__ : Any = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis ) UpperCAmelCase__ : Optional[Any] = set(range(len(mod.weight.size() ) ) ) - axis_set UpperCAmelCase__ : int = pytorch_quantization.utils.reduce_amax(mod.weight , axis=_A , keepdims=_A ).detach() logger.info(F'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''' ) UpperCAmelCase__ : str = amax def __UpperCamelCase( _A : Dict , _A : Tuple=25 , _A : Any=1_80 , _A : Optional[int]=None ): '''simple docstring''' if ignore is None: UpperCAmelCase__ : Dict = [] elif not isinstance(_A , _A ): UpperCAmelCase__ : int = [ignore] UpperCAmelCase__ : Optional[int] = 0 for name, mod in model.named_modules(): if not hasattr(_A , '''weight''' ): continue UpperCAmelCase__ : Dict = max(_A , len(_A ) ) for name, mod in model.named_modules(): UpperCAmelCase__ : str = getattr(_A , '''_input_quantizer''' , _A ) UpperCAmelCase__ : int = getattr(_A , '''_weight_quantizer''' , _A ) if not hasattr(_A , '''weight''' ): continue if type(_A ) in ignore: continue if [True for s in ignore if type(_A ) is str and s in name]: continue UpperCAmelCase__ : Dict = F'''Act:{input_q.extra_repr()}''' UpperCAmelCase__ : int = F'''Wgt:{weight_q.extra_repr()}''' UpperCAmelCase__ : Dict = F'''{name:{name_width}} {act_str} {wgt_str}''' if len(_A ) <= line_width: logger.info(_A ) else: logger.info(F'''{name:{name_width}} {act_str}''' ) logger.info(F'''{' ':{name_width}} {wgt_str}''' ) def __UpperCamelCase( _A : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : str = 0 for name, mod in model.named_modules(): if isinstance(_A , pytorch_quantization.nn.TensorQuantizer ): print(F'''{name:80} {mod}''' ) count += 1 print(F'''{count} TensorQuantizers found in model''' ) def __UpperCamelCase( _A : Dict , _A : Optional[Any] , _A : Union[str, Any] , _A : Union[str, Any] , _A : Dict ): '''simple docstring''' UpperCAmelCase__ : Any = getattr(_A , _A , _A ) if quantizer_mod is not None: assert hasattr(_A , _A ) setattr(_A , _A , _A ) else: logger.warning(F'''{name} has no {quantizer}''' ) def __UpperCamelCase( _A : str , _A : Any , _A : Optional[int]="both" , **_A : List[str] ): '''simple docstring''' UpperCAmelCase__ : Tuple = F'''Warning: changing {which} quantizers of {name:{qname_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' if which in ["input", "both"]: set_quantizer(_A , _A , '''_input_quantizer''' , _A , _A ) if which in ["weight", "both"]: set_quantizer(_A , _A , '''_weight_quantizer''' , _A , _A ) logger.info(_A ) def __UpperCamelCase( _A : Tuple , _A : List[str] , **_A : Optional[Any] ): '''simple docstring''' for name, mod in model.named_modules(): if hasattr(_A , '''_input_quantizer''' ) or hasattr(_A , '''_weight_quantizer''' ): for n in names: if re.search(_A , _A ): set_quantizers(_A , _A , **_A ) elif name.endswith('''_quantizer''' ): for n in names: if re.search(_A , _A ): UpperCAmelCase__ : str = F'''Warning: changing {name:{name_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' setattr(_A , _A , _A ) logger.info(_A )
614
0
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class UpperCamelCase ( unittest.TestCase ): def _lowercase (self : Union[str, Any]) -> Any: __snake_case : List[str] = tempfile.mkdtemp() __snake_case : List[str] = SamImageProcessor() __snake_case : Union[str, Any] = SamProcessor(_A) processor.save_pretrained(self.tmpdirname) def _lowercase (self : str , **_A : Any) -> List[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **_A).image_processor def _lowercase (self : List[Any]) -> Any: shutil.rmtree(self.tmpdirname) def _lowercase (self : List[Any]) -> Dict: __snake_case : Optional[Any] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta)] __snake_case : Dict = [Image.fromarray(np.moveaxis(_A , 0 , -1)) for x in image_inputs] return image_inputs def _lowercase (self : str) -> int: __snake_case : Dict = SamProcessor(image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) __snake_case : Optional[Any] = self.get_image_processor(do_normalize=_A , padding_value=1.0) __snake_case : Any = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_A , padding_value=1.0) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , _A) def _lowercase (self : Dict) -> str: __snake_case : Dict = self.get_image_processor() __snake_case : Optional[Any] = SamProcessor(image_processor=_A) __snake_case : Any = self.prepare_image_inputs() __snake_case : Any = image_processor(_A , return_tensors='np') __snake_case : Optional[Any] = processor(images=_A , return_tensors='np') input_feat_extract.pop('original_sizes') # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes') # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) @require_torch def _lowercase (self : List[str]) -> Optional[Any]: __snake_case : Optional[Any] = self.get_image_processor() __snake_case : Optional[Any] = SamProcessor(image_processor=_A) __snake_case : str = [torch.ones((1, 3, 5, 5))] __snake_case : Optional[Any] = [[17_64, 26_46]] __snake_case : int = [[6_83, 10_24]] __snake_case : Any = processor.post_process_masks(_A , _A , _A) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46)) __snake_case : str = processor.post_process_masks( _A , torch.tensor(_A) , torch.tensor(_A)) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46)) # should also work with np __snake_case : Any = [np.ones((1, 3, 5, 5))] __snake_case : int = processor.post_process_masks(_A , np.array(_A) , np.array(_A)) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46)) __snake_case : List[str] = [[1, 0], [0, 1]] with self.assertRaises(_A): __snake_case : List[Any] = processor.post_process_masks(_A , np.array(_A) , np.array(_A)) @require_vision @require_tf class UpperCamelCase ( unittest.TestCase ): def _lowercase (self : int) -> int: __snake_case : Tuple = tempfile.mkdtemp() __snake_case : Tuple = SamImageProcessor() __snake_case : str = SamProcessor(_A) processor.save_pretrained(self.tmpdirname) def _lowercase (self : Any , **_A : Any) -> int: return AutoProcessor.from_pretrained(self.tmpdirname , **_A).image_processor def _lowercase (self : Dict) -> Optional[Any]: shutil.rmtree(self.tmpdirname) def _lowercase (self : Tuple) -> Tuple: __snake_case : List[Any] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta)] __snake_case : Dict = [Image.fromarray(np.moveaxis(_A , 0 , -1)) for x in image_inputs] return image_inputs def _lowercase (self : Optional[int]) -> Dict: __snake_case : Any = SamProcessor(image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) __snake_case : List[Any] = self.get_image_processor(do_normalize=_A , padding_value=1.0) __snake_case : Optional[int] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_A , padding_value=1.0) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , _A) def _lowercase (self : Optional[Any]) -> Union[str, Any]: __snake_case : Any = self.get_image_processor() __snake_case : Optional[Any] = SamProcessor(image_processor=_A) __snake_case : Any = self.prepare_image_inputs() __snake_case : Tuple = image_processor(_A , return_tensors='np') __snake_case : Optional[int] = processor(images=_A , return_tensors='np') input_feat_extract.pop('original_sizes') # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes') # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) @require_tf def _lowercase (self : Any) -> List[str]: __snake_case : int = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=_A) __snake_case : str = [tf.ones((1, 3, 5, 5))] __snake_case : Any = [[17_64, 26_46]] __snake_case : Any = [[6_83, 10_24]] __snake_case : Dict = processor.post_process_masks(_A , _A , _A , return_tensors='tf') self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46)) __snake_case : List[Any] = processor.post_process_masks( _A , tf.convert_to_tensor(_A) , tf.convert_to_tensor(_A) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46)) # should also work with np __snake_case : Optional[int] = [np.ones((1, 3, 5, 5))] __snake_case : Tuple = processor.post_process_masks( _A , np.array(_A) , np.array(_A) , return_tensors='tf') self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46)) __snake_case : Optional[int] = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError): __snake_case : List[str] = processor.post_process_masks( _A , np.array(_A) , np.array(_A) , return_tensors='tf') @require_vision @require_torchvision class UpperCamelCase ( unittest.TestCase ): def _lowercase (self : List[Any]) -> Union[str, Any]: __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : Tuple = SamProcessor(_A) processor.save_pretrained(self.tmpdirname) def _lowercase (self : List[str] , **_A : Dict) -> List[str]: return AutoProcessor.from_pretrained(self.tmpdirname , **_A).image_processor def _lowercase (self : List[Any]) -> List[str]: shutil.rmtree(self.tmpdirname) def _lowercase (self : str) -> str: __snake_case : str = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta)] __snake_case : List[str] = [Image.fromarray(np.moveaxis(_A , 0 , -1)) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _lowercase (self : Union[str, Any]) -> int: __snake_case : List[Any] = self.get_image_processor() __snake_case : Dict = SamProcessor(image_processor=_A) __snake_case : Union[str, Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5)).astype(np.floataa) __snake_case : List[Any] = [tf.convert_to_tensor(_A)] __snake_case : Union[str, Any] = [torch.tensor(_A)] __snake_case : List[Any] = [[17_64, 26_46]] __snake_case : Tuple = [[6_83, 10_24]] __snake_case : List[Any] = processor.post_process_masks( _A , _A , _A , return_tensors='tf') __snake_case : int = processor.post_process_masks( _A , _A , _A , return_tensors='pt') self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy())) @is_pt_tf_cross_test def _lowercase (self : List[Any]) -> Dict: __snake_case : int = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=_A) __snake_case : str = self.prepare_image_inputs() __snake_case : Optional[int] = image_processor(_A , return_tensors='pt')['pixel_values'].numpy() __snake_case : Dict = processor(images=_A , return_tensors='pt')['pixel_values'].numpy() __snake_case : List[str] = image_processor(_A , return_tensors='tf')['pixel_values'].numpy() __snake_case : Optional[int] = processor(images=_A , return_tensors='tf')['pixel_values'].numpy() self.assertTrue(np.allclose(_A , _A)) self.assertTrue(np.allclose(_A , _A)) self.assertTrue(np.allclose(_A , _A))
192
"""simple docstring""" import math def __UpperCAmelCase ( UpperCAmelCase_ : list , UpperCAmelCase_ : int ) -> int: '''simple docstring''' __snake_case : List[str] = len(UpperCAmelCase_ ) __snake_case : List[Any] = int(math.floor(math.sqrt(UpperCAmelCase_ ) ) ) __snake_case : Any = 0 while arr[min(UpperCAmelCase_ , UpperCAmelCase_ ) - 1] < x: __snake_case : Tuple = step step += int(math.floor(math.sqrt(UpperCAmelCase_ ) ) ) if prev >= n: return -1 while arr[prev] < x: __snake_case : Union[str, Any] = prev + 1 if prev == min(UpperCAmelCase_ , UpperCAmelCase_ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": _a : str= input("Enter numbers separated by a comma:\n").strip() _a : int= [int(item) for item in user_input.split(",")] _a : Optional[Any]= int(input("Enter the number to be searched:\n")) _a : Tuple= jump_search(arr, x) if res == -1: print("Number not found!") else: print(f'''Number {x} is at index {res}''')
192
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = tempfile.mkdtemp() UpperCAmelCase__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCAmelCase__ = os.path.join(self.tmpdirname , 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] ) ) UpperCAmelCase__ = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], } UpperCAmelCase__ = os.path.join(self.tmpdirname , _UpperCAmelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Any , **_UpperCAmelCase : Dict ): """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , **_UpperCAmelCase : List[Any] ): """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , **_UpperCAmelCase : int ): """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" UpperCAmelCase__ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] UpperCAmelCase__ = [Image.fromarray(np.moveaxis(_UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = self.get_rust_tokenizer() UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=_UpperCAmelCase ) UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _UpperCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , _UpperCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _UpperCAmelCase ) self.assertIsInstance(processor_fast.image_processor , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCAmelCase__ = self.get_image_processor(do_normalize=_UpperCAmelCase , padding_value=1.0 ) UpperCAmelCase__ = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = image_processor(_UpperCAmelCase , return_tensors="""np""" ) UpperCAmelCase__ = processor(images=_UpperCAmelCase , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) UpperCAmelCase__ = """lower newer""" UpperCAmelCase__ = processor(text=_UpperCAmelCase ) UpperCAmelCase__ = tokenizer(_UpperCAmelCase , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) UpperCAmelCase__ = """lower newer""" UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(_UpperCAmelCase ): processor() def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) UpperCAmelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCAmelCase__ = processor.batch_decode(_UpperCAmelCase ) UpperCAmelCase__ = tokenizer.batch_decode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = AlignProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase ) UpperCAmelCase__ = """lower newer""" UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
603
'''simple docstring''' import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import 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 ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : Tuple=13 , _UpperCAmelCase : Dict=7 , _UpperCAmelCase : Optional[Any]=True , _UpperCAmelCase : List[Any]=True , _UpperCAmelCase : List[Any]=False , _UpperCAmelCase : int=True , _UpperCAmelCase : Tuple=99 , _UpperCAmelCase : List[Any]=64 , _UpperCAmelCase : Union[str, Any]=5 , _UpperCAmelCase : Tuple=4 , _UpperCAmelCase : str=64 , _UpperCAmelCase : str="gelu" , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : List[str]=5_12 , _UpperCAmelCase : Tuple=16 , _UpperCAmelCase : Dict=2 , _UpperCAmelCase : Tuple=0.02 , _UpperCAmelCase : str=3 , _UpperCAmelCase : Optional[int]=4 , _UpperCAmelCase : Optional[Any]=None , ): """simple docstring""" UpperCAmelCase__ = parent UpperCAmelCase__ = batch_size UpperCAmelCase__ = seq_length UpperCAmelCase__ = is_training UpperCAmelCase__ = use_input_mask UpperCAmelCase__ = use_token_type_ids UpperCAmelCase__ = use_labels UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = type_sequence_label_size UpperCAmelCase__ = initializer_range UpperCAmelCase__ = num_labels UpperCAmelCase__ = num_choices UpperCAmelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" return MPNetConfig.from_pretrained("""microsoft/mpnet-base""" ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ = None if self.use_input_mask: UpperCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : str , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : int ): """simple docstring""" UpperCAmelCase__ = MPNetModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(_UpperCAmelCase , _UpperCAmelCase ) UpperCAmelCase__ = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : Any , _UpperCAmelCase : List[Any] , _UpperCAmelCase : List[Any] ): """simple docstring""" UpperCAmelCase__ = MPNetForQuestionAnswering(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() UpperCAmelCase__ = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , start_positions=_UpperCAmelCase , end_positions=_UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = MPNetForSequenceClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : str , _UpperCAmelCase : List[str] , _UpperCAmelCase : Any ): """simple docstring""" UpperCAmelCase__ = self.num_choices UpperCAmelCase__ = MPNetForMultipleChoice(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() UpperCAmelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase__ = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , labels=_UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str] , _UpperCAmelCase : Any , _UpperCAmelCase : Tuple , _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[int] ): """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = MPNetForTokenClassification(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() UpperCAmelCase__ = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" UpperCAmelCase__ = self.prepare_config_and_inputs() ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) = config_and_inputs UpperCAmelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ : Tuple = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) lowerCAmelCase_ : List[str] = ( { """feature-extraction""": MPNetModel, """fill-mask""": MPNetForMaskedLM, """question-answering""": MPNetForQuestionAnswering, """text-classification""": MPNetForSequenceClassification, """token-classification""": MPNetForTokenClassification, """zero-shot""": MPNetForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ : List[str] = False lowerCAmelCase_ : Optional[Any] = True def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" UpperCAmelCase__ = MPNetModelTester(self ) UpperCAmelCase__ = ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*_UpperCAmelCase ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" UpperCAmelCase__ = MPNetModel.from_pretrained("""microsoft/mpnet-base""" ) UpperCAmelCase__ = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) UpperCAmelCase__ = model(_UpperCAmelCase )[0] UpperCAmelCase__ = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , _UpperCAmelCase ) UpperCAmelCase__ = torch.tensor( [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , _UpperCAmelCase , atol=1E-4 ) )
603
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 UpperCAmelCase_ ( self: Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() def UpperCAmelCase_ ( self: Dict ): '''simple docstring''' UpperCamelCase__: Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) UpperCamelCase__: int = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) UpperCamelCase__: str = "xvjiarui/stable-diffusion-2-inpainting" UpperCamelCase__: List[Any] = FlaxStableDiffusionInpaintPipeline.from_pretrained(__lowerCamelCase , safety_checker=__lowerCamelCase ) UpperCamelCase__: str = "Face of a yellow cat, high resolution, sitting on a park bench" UpperCamelCase__: List[str] = jax.random.PRNGKey(0 ) UpperCamelCase__: Any = 50 UpperCamelCase__: List[str] = jax.device_count() UpperCamelCase__: List[Any] = num_samples * [prompt] UpperCamelCase__: Union[str, Any] = num_samples * [init_image] UpperCamelCase__: Optional[int] = num_samples * [mask_image] UpperCamelCase__: int = pipeline.prepare_inputs(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # shard inputs and rng UpperCamelCase__: Dict = replicate(__lowerCamelCase ) UpperCamelCase__: Any = jax.random.split(__lowerCamelCase , jax.device_count() ) UpperCamelCase__: Optional[int] = shard(__lowerCamelCase ) UpperCamelCase__: Union[str, Any] = shard(__lowerCamelCase ) UpperCamelCase__: str = shard(__lowerCamelCase ) UpperCamelCase__: List[str] = pipeline( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , jit=__lowerCamelCase ) UpperCamelCase__: Any = output.images.reshape(__lowerCamelCase , 512 , 512 , 3 ) UpperCamelCase__: Tuple = images[0, 253:256, 253:256, -1] UpperCamelCase__: Optional[Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase__: Optional[Any] = 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
706
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class _a ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self: Tuple ): '''simple docstring''' UpperCamelCase__: Union[str, Any] = [ "safety_checker/pytorch_model.bin", "safety_checker/model.safetensors", "vae/diffusion_pytorch_model.bin", "vae/diffusion_pytorch_model.safetensors", "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] self.assertTrue(is_safetensors_compatible(__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Optional[int] ): '''simple docstring''' UpperCamelCase__: Tuple = [ "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] self.assertTrue(is_safetensors_compatible(__lowerCamelCase ) ) def UpperCAmelCase_ ( self: str ): '''simple docstring''' UpperCamelCase__: List[str] = [ "safety_checker/pytorch_model.bin", "safety_checker/model.safetensors", "vae/diffusion_pytorch_model.bin", "vae/diffusion_pytorch_model.safetensors", "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", "unet/diffusion_pytorch_model.bin", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Optional[Any] ): '''simple docstring''' UpperCamelCase__: Optional[Any] = [ "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", ] self.assertTrue(is_safetensors_compatible(__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Dict ): '''simple docstring''' UpperCamelCase__: Tuple = [ "safety_checker/pytorch_model.bin", "safety_checker/model.safetensors", "vae/diffusion_pytorch_model.bin", "vae/diffusion_pytorch_model.safetensors", "text_encoder/pytorch_model.bin", # Removed: 'text_encoder/model.safetensors', "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] self.assertFalse(is_safetensors_compatible(__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Union[str, Any] ): '''simple docstring''' UpperCamelCase__: List[str] = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "text_encoder/model.fp16.safetensors", "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] UpperCamelCase__: int = "fp16" self.assertTrue(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Any ): '''simple docstring''' UpperCamelCase__: List[Any] = [ "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] UpperCamelCase__: Optional[int] = "fp16" self.assertTrue(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Union[str, Any] ): '''simple docstring''' UpperCamelCase__: List[Any] = [ "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] UpperCamelCase__: Tuple = "fp16" self.assertTrue(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) ) def UpperCAmelCase_ ( self: str ): '''simple docstring''' UpperCamelCase__: Tuple = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "text_encoder/model.fp16.safetensors", "unet/diffusion_pytorch_model.fp16.bin", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] UpperCamelCase__: Union[str, Any] = "fp16" self.assertFalse(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) ) def UpperCAmelCase_ ( self: Union[str, Any] ): '''simple docstring''' UpperCamelCase__: str = [ "text_encoder/pytorch_model.fp16.bin", "text_encoder/model.fp16.safetensors", ] UpperCamelCase__: List[Any] = "fp16" self.assertTrue(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) ) def UpperCAmelCase_ ( self: int ): '''simple docstring''' UpperCamelCase__: Dict = [ "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", ] UpperCamelCase__: Dict = "fp16" self.assertTrue(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) ) def UpperCAmelCase_ ( self: List[Any] ): '''simple docstring''' UpperCamelCase__: Any = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", # 'text_encoder/model.fp16.safetensors', "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] UpperCamelCase__: Optional[int] = "fp16" self.assertFalse(is_safetensors_compatible(__lowerCamelCase , variant=__lowerCamelCase ) )
221
0
'''simple docstring''' from importlib import import_module from .logging import get_logger SCREAMING_SNAKE_CASE_: Any =get_logger(__name__) class __A : def __init__(self : str , __a : Optional[int] , __a : int=None ): UpperCAmelCase_ = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__" ): setattr(self , __a , getattr(__a , __a ) ) UpperCAmelCase_ = module._original_module if isinstance(__a , _PatchedModuleObj ) else module class __A : a__ : List[Any] = [] def __init__(self : Dict , __a : List[Any] , __a : str , __a : Dict , __a : int=None ): UpperCAmelCase_ = obj UpperCAmelCase_ = target UpperCAmelCase_ = new UpperCAmelCase_ = target.split("." )[0] UpperCAmelCase_ = {} UpperCAmelCase_ = attrs or [] def __enter__(self : Union[str, Any] ): *UpperCAmelCase_ , UpperCAmelCase_ = self.target.split("." ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__a ) ): try: UpperCAmelCase_ = import_module(".".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCAmelCase_ = getattr(self.obj , __a ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__a , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCAmelCase_ = obj_attr # patch at top level setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs ) ) UpperCAmelCase_ = getattr(self.obj , __a ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a ) , attrs=self.attrs ) ) UpperCAmelCase_ = getattr(__a , __a ) # finally set the target attribute setattr(__a , __a , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCAmelCase_ = getattr(import_module(".".join(__a ) ) , __a ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __a ) is attr_value: UpperCAmelCase_ = getattr(self.obj , __a ) setattr(self.obj , __a , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCAmelCase_ = globals()["__builtins__"][target_attr] setattr(self.obj , __a , self.new ) else: raise RuntimeError(f"""Tried to patch attribute {target_attr} instead of a submodule.""" ) def __exit__(self : str , *__a : Optional[int] ): for attr in list(self.original ): setattr(self.obj , __a , self.original.pop(__a ) ) def _lowercase (self : int ): self.__enter__() self._active_patches.append(self ) def _lowercase (self : int ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
78
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
1
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class SCREAMING_SNAKE_CASE ( yaml.SafeLoader ): '''simple docstring''' def _UpperCamelCase ( self :Any , __magic_name__ :str ) -> Dict: '''simple docstring''' a__ = [self.constructed_objects[key_node] for key_node, _ in node.value] a__ = [tuple(UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else key for key in keys] a__ = Counter(UpperCAmelCase_ ) a__ = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}" ) def _UpperCamelCase ( self :Dict , __magic_name__ :int , __magic_name__ :Tuple=False ) -> Optional[Any]: '''simple docstring''' a__ = super().construct_mapping(UpperCAmelCase_ , deep=UpperCAmelCase_ ) self._check_no_duplicates_on_constructed_node(UpperCAmelCase_ ) return mapping def __snake_case ( UpperCamelCase ) -> Any: """simple docstring""" a__ = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: a__ = full_content[1:].index('''---''' ) + 1 a__ = '''\n'''.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_snake_case ) class SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' snake_case__ : Any = {"""train_eval_index"""} # train-eval-index in the YAML metadata @classmethod def _UpperCamelCase ( cls :Any , __magic_name__ :Optional[Any] ) -> Dict: '''simple docstring''' with open(UpperCAmelCase_ , encoding='''utf-8''' ) as readme_file: a__ , a__ = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(UpperCAmelCase_ ) else: return cls() def _UpperCamelCase ( self :Any , __magic_name__ :Union[str, Any] ) -> List[Any]: '''simple docstring''' if path.exists(): with open(UpperCAmelCase_ , encoding='''utf-8''' ) as readme_file: a__ = readme_file.read() else: a__ = None a__ = self._to_readme(UpperCAmelCase_ ) with open(UpperCAmelCase_ , '''w''' , encoding='''utf-8''' ) as readme_file: readme_file.write(UpperCAmelCase_ ) def _UpperCamelCase ( self :Optional[Any] , __magic_name__ :Union[str, Any] = None ) -> int: '''simple docstring''' if readme_content is not None: a__ , a__ = _split_yaml_from_readme(UpperCAmelCase_ ) a__ = '''---\n''' + self.to_yaml_string() + '''---\n''' + content else: a__ = '''---\n''' + self.to_yaml_string() + '''---\n''' return full_content @classmethod def _UpperCamelCase ( cls :Tuple , __magic_name__ :Optional[Any] ) -> Any: '''simple docstring''' a__ = yaml.load(UpperCAmelCase_ , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields a__ = { (key.replace('''-''' , '''_''' ) if key.replace('''-''' , '''_''' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**UpperCAmelCase_ ) def _UpperCamelCase ( self :int ) -> List[str]: '''simple docstring''' return yaml.safe_dump( { (key.replace('''_''' , '''-''' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=UpperCAmelCase_ , allow_unicode=UpperCAmelCase_ , encoding='''utf-8''' , ).decode('''utf-8''' ) __lowerCAmelCase : List[str] = { '''image-classification''': [], '''translation''': [], '''image-segmentation''': [], '''fill-mask''': [], '''automatic-speech-recognition''': [], '''token-classification''': [], '''sentence-similarity''': [], '''audio-classification''': [], '''question-answering''': [], '''summarization''': [], '''zero-shot-classification''': [], '''table-to-text''': [], '''feature-extraction''': [], '''other''': [], '''multiple-choice''': [], '''text-classification''': [], '''text-to-image''': [], '''text2text-generation''': [], '''zero-shot-image-classification''': [], '''tabular-classification''': [], '''tabular-regression''': [], '''image-to-image''': [], '''tabular-to-text''': [], '''unconditional-image-generation''': [], '''text-retrieval''': [], '''text-to-speech''': [], '''object-detection''': [], '''audio-to-audio''': [], '''text-generation''': [], '''conversational''': [], '''table-question-answering''': [], '''visual-question-answering''': [], '''image-to-text''': [], '''reinforcement-learning''': [], '''voice-activity-detection''': [], '''time-series-forecasting''': [], '''document-question-answering''': [], } if __name__ == "__main__": from argparse import ArgumentParser __lowerCAmelCase : Optional[int] = ArgumentParser(usage='''Validate the yaml metadata block of a README.md file.''') ap.add_argument('''readme_filepath''') __lowerCAmelCase : str = ap.parse_args() __lowerCAmelCase : Dict = Path(args.readme_filepath) __lowerCAmelCase : List[Any] = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
711
"""simple docstring""" import math import qiskit def __snake_case ( UpperCamelCase = 1 , UpperCamelCase = 1 , UpperCamelCase = 1 ) -> qiskit.result.counts.Counts: """simple docstring""" if ( isinstance(UpperCamelCase , UpperCamelCase ) or isinstance(UpperCamelCase , UpperCamelCase ) or isinstance(UpperCamelCase , UpperCamelCase ) ): raise TypeError('''inputs must be integers.''' ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError('''inputs must be positive.''' ) if ( (math.floor(UpperCamelCase ) != input_a) or (math.floor(UpperCamelCase ) != input_a) or (math.floor(UpperCamelCase ) != carry_in) ): raise ValueError('''inputs must be exact integers.''' ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError('''inputs must be less or equal to 2.''' ) # build registers a__ = qiskit.QuantumRegister(4 , '''qr''' ) a__ = qiskit.ClassicalRegister(2 , '''cr''' ) # list the entries a__ = [input_a, input_a, carry_in] a__ = qiskit.QuantumCircuit(UpperCamelCase , UpperCamelCase ) for i in range(0 , 3 ): if entry[i] == 2: quantum_circuit.h(UpperCamelCase ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(UpperCamelCase ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(UpperCamelCase ) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate quantum_circuit.cx(0 , 1 ) quantum_circuit.ccx(1 , 2 , 3 ) quantum_circuit.cx(1 , 2 ) quantum_circuit.cx(0 , 1 ) quantum_circuit.measure([2, 3] , UpperCamelCase ) # measure the last two qbits a__ = qiskit.Aer.get_backend('''aer_simulator''' ) a__ = qiskit.execute(UpperCamelCase , UpperCamelCase , shots=1_000 ) return job.result().get_counts(UpperCamelCase ) if __name__ == "__main__": print(f"Total sum count for state is: {quantum_full_adder(1, 1, 1)}")
158
0
def a_ ( SCREAMING_SNAKE_CASE__ : int = 1_000_000 ): '''simple docstring''' _lowerCamelCase : str =[i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , UpperCAmelCase_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
464
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowercase_ ( A ): __lowerCamelCase = (DDIMParallelScheduler,) __lowerCamelCase = (("eta", 0.0), ("num_inference_steps", 5_0)) def _snake_case ( self , **__A ) -> List[str]: SCREAMING_SNAKE_CASE_ : Optional[Any] ={ '''num_train_timesteps''': 1_000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**__A ) return config def _snake_case ( self , **__A ) -> List[Any]: SCREAMING_SNAKE_CASE_ : int =self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : str =self.get_scheduler_config(**__A ) SCREAMING_SNAKE_CASE_ : List[Any] =scheduler_class(**__A ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] =10, 0.0 SCREAMING_SNAKE_CASE_ : List[str] =self.dummy_model() SCREAMING_SNAKE_CASE_ : Union[str, Any] =self.dummy_sample_deter scheduler.set_timesteps(__A ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ : Optional[int] =model(__A , __A ) SCREAMING_SNAKE_CASE_ : List[Any] =scheduler.step(__A , __A , __A , __A ).prev_sample return sample def _snake_case ( self ) -> Optional[Any]: for timesteps in [100, 500, 1_000]: self.check_over_configs(num_train_timesteps=__A ) def _snake_case ( self ) -> Optional[int]: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__A ) SCREAMING_SNAKE_CASE_ : Dict =self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[Any] =self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE_ : Dict =scheduler_class(**__A ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def _snake_case ( self ) -> Dict: for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__A , beta_end=__A ) def _snake_case ( self ) -> str: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__A ) def _snake_case ( self ) -> List[str]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__A ) def _snake_case ( self ) -> List[Any]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=__A ) def _snake_case ( self ) -> int: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__A ) def _snake_case ( self ) -> Tuple: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__A ) def _snake_case ( self ) -> List[Any]: self.check_over_configs(thresholding=__A ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__A , prediction_type=__A , sample_max_value=__A , ) def _snake_case ( self ) -> Dict: for t in [1, 10, 49]: self.check_over_forward(time_step=__A ) def _snake_case ( self ) -> Dict: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__A , num_inference_steps=__A ) def _snake_case ( self ) -> int: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__A , eta=__A ) def _snake_case ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE_ : List[Any] =self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] =self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : List[str] =scheduler_class(**__A ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def _snake_case ( self ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ : List[str] =self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] =self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : str =scheduler_class(**__A ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] =10, 0.0 scheduler.set_timesteps(__A ) SCREAMING_SNAKE_CASE_ : List[str] =self.dummy_model() SCREAMING_SNAKE_CASE_ : str =self.dummy_sample_deter SCREAMING_SNAKE_CASE_ : int =self.dummy_sample_deter + 0.1 SCREAMING_SNAKE_CASE_ : Tuple =self.dummy_sample_deter - 0.1 SCREAMING_SNAKE_CASE_ : Union[str, Any] =samplea.shape[0] SCREAMING_SNAKE_CASE_ : List[str] =torch.stack([samplea, samplea, samplea] , dim=0 ) SCREAMING_SNAKE_CASE_ : Any =torch.arange(__A )[0:3, None].repeat(1 , __A ) SCREAMING_SNAKE_CASE_ : Dict =model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE_ : Optional[int] =scheduler.batch_step_no_noise(__A , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __A ) SCREAMING_SNAKE_CASE_ : str =torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE_ : int =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def _snake_case ( self ) -> Any: SCREAMING_SNAKE_CASE_ : List[str] =self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] =torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def _snake_case ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ : str =self.full_loop(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ : List[Any] =torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE_ : str =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def _snake_case ( self ) -> Dict: # We specify different beta, so that the first alpha is 0.99 SCREAMING_SNAKE_CASE_ : Tuple =self.full_loop(set_alpha_to_one=__A , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple =torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE_ : int =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def _snake_case ( self ) -> Optional[Any]: # We specify different beta, so that the first alpha is 0.99 SCREAMING_SNAKE_CASE_ : List[str] =self.full_loop(set_alpha_to_one=__A , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ : Optional[int] =torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE_ : Tuple =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
443
0
def UpperCAmelCase__( UpperCAmelCase__ :list ): '''simple docstring''' if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information" ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] a = grid[0] for row_n in range(1 , len(UpperCAmelCase__ ) ): a = grid[row_n] a = fill_row(UpperCAmelCase__ , UpperCAmelCase__ ) a = grid[row_n] return grid[-1][-1] def UpperCAmelCase__( UpperCAmelCase__ :list , UpperCAmelCase__ :list ): '''simple docstring''' current_row[0] += row_above[0] for cell_n in range(1 , len(UpperCAmelCase__ ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
714
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowercase ( UpperCAmelCase__ ): _UpperCAmelCase = 42 _UpperCAmelCase = 42 def __init__( self : Optional[Any] , __lowerCAmelCase : UNetaDModel , __lowerCAmelCase : ScoreSdeVeScheduler ) -> str: """simple docstring""" super().__init__() self.register_modules(unet=__lowerCAmelCase , scheduler=__lowerCAmelCase ) @torch.no_grad() def __call__( self : int , __lowerCAmelCase : int = 1 , __lowerCAmelCase : int = 2000 , __lowerCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __lowerCAmelCase : Optional[str] = "pil" , __lowerCAmelCase : bool = True , **__lowerCAmelCase : Any , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" a = self.unet.config.sample_size a = (batch_size, 3, img_size, img_size) a = self.unet a = randn_tensor(__lowerCAmelCase , generator=__lowerCAmelCase ) * self.scheduler.init_noise_sigma a = sample.to(self.device ) self.scheduler.set_timesteps(__lowerCAmelCase ) self.scheduler.set_sigmas(__lowerCAmelCase ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): a = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): a = self.unet(__lowerCAmelCase , __lowerCAmelCase ).sample a = self.scheduler.step_correct(__lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample # prediction step a = model(__lowerCAmelCase , __lowerCAmelCase ).sample a = self.scheduler.step_pred(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ) a , a = output.prev_sample, output.prev_sample_mean a = sample_mean.clamp(0 , 1 ) a = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a = self.numpy_to_pil(__lowerCAmelCase ) if not return_dict: return (sample,) return ImagePipelineOutput(images=__lowerCAmelCase )
32
0
"""simple docstring""" def __A ( a_ :Optional[int]) -> int: __a : int = 0 __a : Optional[int] = len(a_) for i in range(n - 1): for j in range(i + 1 , a_): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def __A ( a_ :str) -> List[str]: if len(a_) <= 1: return arr, 0 __a : Optional[Any] = len(a_) // 2 __a : str = arr[0:mid] __a : List[Any] = arr[mid:] __a , __a : List[str] = count_inversions_recursive(a_) __a , __a : str = count_inversions_recursive(a_) __a , __a : int = _count_cross_inversions(a_ , a_) __a : List[str] = inversion_p + inversions_q + cross_inversions return c, num_inversions def __A ( a_ :Tuple , a_ :List[str]) -> str: __a : List[str] = [] __a : Dict = 0 while i < len(a_) and j < len(a_): 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(a_) - i r.append(q[j]) j += 1 else: r.append(p[i]) i += 1 if i < len(a_): r.extend(p[i:]) else: r.extend(q[j:]) return r, num_inversion def __A ( ) -> Any: __a : Dict = [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) __a : Any = count_inversions_bf(a_) __a , __a : Dict = count_inversions_recursive(a_) assert num_inversions_bf == num_inversions_recursive == 8 print('''number of inversions = ''' , a_) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() __a : str = count_inversions_bf(a_) __a , __a : List[Any] = count_inversions_recursive(a_) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , a_) # an empty list should also have zero inversions __a : Dict = [] __a : List[Any] = count_inversions_bf(a_) __a , __a : Tuple = count_inversions_recursive(a_) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , a_) if __name__ == "__main__": main()
52
'''simple docstring''' 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 UpperCamelCase__ = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co UpperCamelCase__ = 'main' # Default branch name UpperCamelCase__ = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) UpperCamelCase__ = 'aaaaaaa' # This commit does not exist, so we should 404. UpperCamelCase__ = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes UpperCamelCase__ = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" print("Welcome!" ) yield print("Bye!" ) @contextlib.contextmanager def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" print("Bonjour!" ) yield print("Au revoir!" ) class _UpperCAmelCase ( unittest.TestCase ): def lowerCAmelCase__ ( self : int ): '''simple docstring''' assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers" ) is not None class _UpperCAmelCase ( unittest.TestCase ): @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def lowerCAmelCase__ ( self : str , a : List[str] ): '''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 lowerCAmelCase__ ( self : List[str] , a : Optional[int] ): '''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 lowerCAmelCase__ ( self : Tuple , a : 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 lowerCAmelCase__ ( self : Tuple ): '''simple docstring''' self.assertEqual(find_labels(a ) , ["labels"] ) self.assertEqual(find_labels(a ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(a ) , ["start_positions", "end_positions"] ) class _UpperCAmelCase ( snake_case ): pass self.assertEqual(find_labels(a ) , ["labels"] ) @require_tf def lowerCAmelCase__ ( self : int ): '''simple docstring''' self.assertEqual(find_labels(a ) , ["labels"] ) self.assertEqual(find_labels(a ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(a ) , ["start_positions", "end_positions"] ) class _UpperCAmelCase ( snake_case ): pass self.assertEqual(find_labels(a ) , ["labels"] ) @require_flax def lowerCAmelCase__ ( self : str ): '''simple docstring''' self.assertEqual(find_labels(a ) , [] ) self.assertEqual(find_labels(a ) , [] ) self.assertEqual(find_labels(a ) , [] ) class _UpperCAmelCase ( snake_case ): pass self.assertEqual(find_labels(a ) , [] )
620
0
from __future__ import annotations from typing import Any class UpperCamelCase__ : '''simple docstring''' def __init__( self , A = 6 ) ->List[str]: UpperCAmelCase__ :Node | None = None UpperCAmelCase__ :Node | None = None self.create_linked_list(A_ ) def A__ ( self , A ) ->Tuple: UpperCAmelCase__ :Tuple = Node() UpperCAmelCase__ :str = current_node UpperCAmelCase__ :str = current_node UpperCAmelCase__ :Dict = current_node for _ in range(1 , A_ ): UpperCAmelCase__ :str = Node() UpperCAmelCase__ :Union[str, Any] = current_node UpperCAmelCase__ :str = previous_node UpperCAmelCase__ :Optional[Any] = current_node UpperCAmelCase__ :int = self.front UpperCAmelCase__ :List[Any] = previous_node def A__ ( self ) ->Optional[Any]: return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) ->int: self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , A ) ->Union[str, Any]: if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCAmelCase__ :List[str] = self.rear.next if self.rear: UpperCAmelCase__ :Dict = data def A__ ( self ) ->Optional[Any]: self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCAmelCase__ :Union[str, Any] = self.front.data UpperCAmelCase__ :Any = None return data UpperCAmelCase__ :str = self.front UpperCAmelCase__ :List[Any] = old_front.next UpperCAmelCase__ :Any = old_front.data UpperCAmelCase__ :str = None return data def A__ ( self ) ->Union[str, Any]: if self.is_empty(): raise Exception('Empty Queue' ) def A__ ( self ) ->int: if self.rear and self.rear.next == self.front: raise Exception('Full Queue' ) class UpperCamelCase__ : '''simple docstring''' def __init__( self ) ->Optional[int]: UpperCAmelCase__ :Any | None = None UpperCAmelCase__ :Node | None = None UpperCAmelCase__ :Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
716
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class UpperCamelCase__ ( unittest.TestCase): '''simple docstring''' def A__ ( self ) ->int: UpperCAmelCase__ :Union[str, Any] = 10 def A__ ( self ) ->Optional[int]: UpperCAmelCase__ :Optional[int] = [1, 2, 3, 4] UpperCAmelCase__ :Any = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(A , self.block_size , 0 ) , A ) def A__ ( self ) ->Optional[Any]: UpperCAmelCase__ :List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] UpperCAmelCase__ :Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(A , self.block_size , 0 ) , A ) def A__ ( self ) ->Tuple: UpperCAmelCase__ :Optional[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] UpperCAmelCase__ :str = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(A , self.block_size , 0 ) , A ) def A__ ( self ) ->List[Any]: UpperCAmelCase__ :Dict = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' UpperCAmelCase__ , UpperCAmelCase__ :Any = process_story(A ) self.assertEqual(A , [] ) def A__ ( self ) ->List[str]: UpperCAmelCase__ :str = '' UpperCAmelCase__ , UpperCAmelCase__ :Any = process_story(A ) self.assertEqual(A , [] ) self.assertEqual(A , [] ) def A__ ( self ) ->int: UpperCAmelCase__ :List[Any] = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) UpperCAmelCase__ , UpperCAmelCase__ :List[Any] = process_story(A ) UpperCAmelCase__ :Union[str, Any] = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(A , A ) UpperCAmelCase__ :Optional[int] = ['It was the best of times.'] self.assertEqual(A , A ) def A__ ( self ) ->Dict: UpperCAmelCase__ :List[Any] = torch.tensor([1, 2, 3, 4] ) UpperCAmelCase__ :int = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(A , 0 ).numpy() , expected.numpy() ) def A__ ( self ) ->List[str]: UpperCAmelCase__ :Optional[int] = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) UpperCAmelCase__ :List[Any] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(A , 23 ).numpy() , expected.numpy() ) def A__ ( self ) ->Any: UpperCAmelCase__ :Tuple = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) UpperCAmelCase__ :Dict = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(A , 1 ).numpy() , expected.numpy() ) def A__ ( self ) ->Optional[Any]: UpperCAmelCase__ :str = 1_01 UpperCAmelCase__ :Optional[Any] = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_01, 5, 6], [1, 1_01, 3, 4, 1_01, 6]] ) UpperCAmelCase__ :str = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) UpperCAmelCase__ :List[str] = compute_token_type_ids(A , A ) np.testing.assert_array_equal(A , A )
433
0
import heapq def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(_a , [-1 * len(_a), (key, value)]) # chosen_vertices = set of chosen vertices SCREAMING_SNAKE_CASE : str = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices SCREAMING_SNAKE_CASE : str = heapq.heappop(_a)[1][0] chosen_vertices.add(_a) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: SCREAMING_SNAKE_CASE : List[str] = elem[1][1].index(_a) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(_a) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() a_ = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
25
"""simple docstring""" def lowerCAmelCase_ (_SCREAMING_SNAKE_CASE :int = 1 , _SCREAMING_SNAKE_CASE :int = 1000 ) -> int: a_ : Tuple = 1 a_ : Optional[int] = 0 for divide_by_number in range(_SCREAMING_SNAKE_CASE , digit + 1 ): a_ : list[int] = [] a_ : Any = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(_SCREAMING_SNAKE_CASE ): a_ : Optional[Any] = len(_SCREAMING_SNAKE_CASE ) a_ : Union[str, Any] = divide_by_number else: has_been_divided.append(_SCREAMING_SNAKE_CASE ) a_ : Any = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
473
0
'''simple docstring''' def snake_case ( a_ : int ) -> int: """simple docstring""" UpperCamelCase_ : int = abs(a_ ) UpperCamelCase_ : Tuple = 0 while n > 0: res += n % 10 n //= 10 return res def snake_case ( a_ : int ) -> int: """simple docstring""" UpperCamelCase_ : Optional[int] = abs(a_ ) return n if n < 10 else n % 10 + sum_of_digits(n // 10 ) def snake_case ( a_ : int ) -> int: """simple docstring""" return sum(int(a_ ) for c in str(abs(a_ ) ) ) def snake_case ( ) -> None: """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(a_ : Callable , a_ : int ) -> None: UpperCamelCase_ : Any = f"{func.__name__}({value})" UpperCamelCase_ : str = timeit(f"__main__.{call}" , setup="""import __main__""" ) print(f"{call:56} = {func(a_ )} -- {timing:.4f} seconds" ) for value in (262_144, 1_125_899_906_842_624, 1_267_650_600_228_229_401_496_703_205_376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(a_ , a_ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
713
'''simple docstring''' from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand UpperCamelCase =logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case ( a_ : str ) -> int: """simple docstring""" if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(a_ ): return ext raise Exception( f"Unable to determine file format from file extension {path}. " f"Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}" ) def snake_case ( a_ : List[Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ : Any = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) UpperCamelCase_ : List[Any] = try_infer_format_from_ext(args.input ) if args.format == """infer""" else args.format UpperCamelCase_ : Tuple = PipelineDataFormat.from_str( format=a_ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(a_ , a_ ) class A ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , __lowerCAmelCase , __lowerCAmelCase ): UpperCamelCase_ : Union[str, Any] = nlp UpperCamelCase_ : Optional[Any] = reader @staticmethod def _UpperCAmelCase ( __lowerCAmelCase ): UpperCamelCase_ : List[str] = parser.add_parser("""run""" , help="""Run a pipeline through the CLI""" ) run_parser.add_argument("""--task""" , choices=get_supported_tasks() , help="""Task to run""" ) run_parser.add_argument("""--input""" , type=__lowerCAmelCase , help="""Path to the file to use for inference""" ) run_parser.add_argument("""--output""" , type=__lowerCAmelCase , help="""Path to the file that will be used post to write results.""" ) run_parser.add_argument("""--model""" , type=__lowerCAmelCase , help="""Name or path to the model to instantiate.""" ) run_parser.add_argument("""--config""" , type=__lowerCAmelCase , help="""Name or path to the model's config to instantiate.""" ) run_parser.add_argument( """--tokenizer""" , type=__lowerCAmelCase , help="""Name of the tokenizer to use. (default: same as the model name)""" ) run_parser.add_argument( """--column""" , type=__lowerCAmelCase , help="""Name of the column to use as input. (For multi columns input as QA use column1,columns2)""" , ) run_parser.add_argument( """--format""" , type=__lowerCAmelCase , default="""infer""" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="""Input format to read from""" , ) run_parser.add_argument( """--device""" , type=__lowerCAmelCase , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) run_parser.add_argument("""--overwrite""" , action="""store_true""" , help="""Allow overwriting the output file.""" ) run_parser.set_defaults(func=__lowerCAmelCase ) def _UpperCAmelCase ( self ): UpperCamelCase_ , UpperCamelCase_ : str = self._nlp, [] for entry in self._reader: UpperCamelCase_ : List[Any] = nlp(**__lowerCAmelCase ) if self._reader.is_multi_columns else nlp(__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ): outputs.append(__lowerCAmelCase ) else: outputs += output # Saving data if self._nlp.binary_output: UpperCamelCase_ : int = self._reader.save_binary(__lowerCAmelCase ) logger.warning(F"Current pipeline requires output to be in binary format, saving at {binary_path}" ) else: self._reader.save(__lowerCAmelCase )
543
0
'''simple docstring''' from __future__ import annotations def a_ ( __UpperCAmelCase ) -> list[int]: """simple docstring""" snake_case: str =2 snake_case: List[Any] =[] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(__UpperCAmelCase ) if n > 1: factors.append(__UpperCAmelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
350
'''simple docstring''' import unittest from knapsack import knapsack as k class a_ ( unittest.TestCase ): def UpperCamelCase ( self : str ) -> List[Any]: snake_case: Optional[Any] =0 snake_case: List[str] =[0] snake_case: List[str] =[0] snake_case: Union[str, Any] =len(a_ ) self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 0 ) snake_case: Union[str, Any] =[6_0] snake_case: str =[1_0] snake_case: List[str] =len(a_ ) self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 0 ) def UpperCamelCase ( self : int ) -> Optional[Any]: snake_case: Optional[int] =3 snake_case: Dict =[1, 2, 3] snake_case: List[Any] =[3, 2, 1] snake_case: Tuple =len(a_ ) self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 5 ) def UpperCamelCase ( self : List[str] ) -> str: snake_case: Any =5_0 snake_case: str =[6_0, 1_0_0, 1_2_0] snake_case: Any =[1_0, 2_0, 3_0] snake_case: Tuple =len(a_ ) self.assertEqual(k.knapsack(a_ , a_ , a_ , a_ ) , 2_2_0 ) if __name__ == "__main__": unittest.main()
350
1
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class snake_case__ ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase ( self : Optional[Any] ) -> Dict: UpperCAmelCase_ = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) UpperCAmelCase_ = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) UpperCAmelCase_ = '''The dog is cute and lives in the garden house''' UpperCAmelCase_ = jnp.array([tokenizer.encode(lowerCAmelCase_ )] ) UpperCAmelCase_ = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim UpperCAmelCase_ = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) UpperCAmelCase_ = model(lowerCAmelCase_ )['''last_hidden_state'''] self.assertEqual(output.shape , lowerCAmelCase_ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , lowerCAmelCase_ , atol=1e-3 ) )
719
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def _lowerCAmelCase ( __magic_name__ :list , __magic_name__ :list , __magic_name__ :list , __magic_name__ :list , __magic_name__ :list ): UpperCAmelCase_ = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__magic_name__ )] ) UpperCAmelCase_ = np.array(__magic_name__ ) UpperCAmelCase_ = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , __magic_name__ ) ) , x.transpose() ) , __magic_name__ ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def _lowerCAmelCase ( __magic_name__ :list , __magic_name__ :list , __magic_name__ :list ): UpperCAmelCase_ = (1, 2, 1) UpperCAmelCase_ = (1, 1, 0, 7) UpperCAmelCase_ = SARIMAX( __magic_name__ , exog=__magic_name__ , order=__magic_name__ , seasonal_order=__magic_name__ ) UpperCAmelCase_ = model.fit(disp=__magic_name__ , maxiter=6_0_0 , method='''nm''' ) UpperCAmelCase_ = model_fit.predict(1 , len(__magic_name__ ) , exog=[test_match] ) return result[0] def _lowerCAmelCase ( __magic_name__ :list , __magic_name__ :list , __magic_name__ :list ): UpperCAmelCase_ = SVR(kernel='''rbf''' , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(__magic_name__ , __magic_name__ ) UpperCAmelCase_ = regressor.predict(__magic_name__ ) return y_pred[0] def _lowerCAmelCase ( __magic_name__ :list ): train_user.sort() UpperCAmelCase_ = np.percentile(__magic_name__ , 2_5 ) UpperCAmelCase_ = np.percentile(__magic_name__ , 7_5 ) UpperCAmelCase_ = qa - qa UpperCAmelCase_ = qa - (iqr * 0.1) return low_lim def _lowerCAmelCase ( __magic_name__ :list , __magic_name__ :float ): UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 for i in list_vote: if i > actual_result: UpperCAmelCase_ = not_safe + 1 else: if abs(abs(__magic_name__ ) - abs(__magic_name__ ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) _lowerCamelCase : List[str] = [[1_8231, 0.0, 1], [2_2621, 1.0, 2], [1_5675, 0.0, 3], [2_3583, 1.0, 4]] _lowerCamelCase : Any = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) _lowerCamelCase : Optional[Any] = Normalizer().fit_transform(data_input_df.values) # split data _lowerCamelCase : List[str] = normalize_df[:, 2].tolist() _lowerCamelCase : Dict = normalize_df[:, 0].tolist() _lowerCamelCase : Optional[Any] = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) _lowerCamelCase : Union[str, Any] = normalize_df[:, [1, 2]].tolist() _lowerCamelCase : Any = x[: len(x) - 1] _lowerCamelCase : Optional[int] = x[len(x) - 1 :] # for linear regression & sarimax _lowerCamelCase : List[str] = total_date[: len(total_date) - 1] _lowerCamelCase : Any = total_user[: len(total_user) - 1] _lowerCamelCase : Dict = total_match[: len(total_match) - 1] _lowerCamelCase : Any = total_date[len(total_date) - 1 :] _lowerCamelCase : List[str] = total_user[len(total_user) - 1 :] _lowerCamelCase : Any = total_match[len(total_match) - 1 :] # voting system with forecasting _lowerCamelCase : List[str] = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data _lowerCamelCase : int = '' if data_safety_checker(res_vote, tst_user) else 'not ' print('Today\'s data is {not_str}safe.')
407
0
'''simple docstring''' import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __lowerCamelCase = '''.''' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) __lowerCamelCase = [ '''Assert''', '''AssignVariableOp''', '''EmptyTensorList''', '''MergeV2Checkpoints''', '''ReadVariableOp''', '''ResourceGather''', '''RestoreV2''', '''SaveV2''', '''ShardedFilename''', '''StatefulPartitionedCall''', '''StaticRegexFullMatch''', '''VarHandleOp''', ] def a__ ( UpperCamelCase_ : str, UpperCamelCase_ : List[Any], UpperCamelCase_ : Dict ): UpperCAmelCase__ :Optional[int] = SavedModel() UpperCAmelCase__ :List[str] = [] with open(os.path.join(A__, '''utils''', '''tf_ops''', '''onnx.json''' ) ) as f: UpperCAmelCase__ :Optional[int] = json.load(A__ )['''opsets'''] for i in range(1, opset + 1 ): onnx_ops.extend(onnx_opsets[str(A__ )] ) with open(A__, '''rb''' ) as f: saved_model.ParseFromString(f.read() ) UpperCAmelCase__ :Optional[int] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want UpperCAmelCase__ :Tuple = sorted(A__ ) UpperCAmelCase__ :Optional[Any] = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(A__ ) if strict and len(A__ ) > 0: raise Exception(F'''Found the following incompatible ops for the opset {opset}:\n''' + incompatible_ops ) elif len(A__ ) > 0: print(F'''Found the following incompatible ops for the opset {opset}:''' ) print(*A__, sep='''\n''' ) else: print(F'''The saved model {saved_model_path} can properly be converted with ONNX.''' ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() parser.add_argument('''--saved_model_path''', help='''Path of the saved model to check (the .pb file).''') parser.add_argument( '''--opset''', default=12, type=int, help='''The ONNX opset against which the model has to be tested.''' ) parser.add_argument( '''--framework''', choices=['''onnx'''], default='''onnx''', help='''Frameworks against which to test the saved model.''' ) parser.add_argument( '''--strict''', action='''store_true''', help='''Whether make the checking strict (raise errors) or not (raise warnings)''' ) __lowerCamelCase = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
467
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowercase : '''simple docstring''' def __init__( self , _snake_case , _snake_case=2 , _snake_case=3 , _snake_case=4 , _snake_case=2 , _snake_case=7 , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=99 , _snake_case=36 , _snake_case=3 , _snake_case=4 , _snake_case=37 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=512 , _snake_case=16 , _snake_case=2 , _snake_case=0.02 , _snake_case=6 , _snake_case=6 , _snake_case=3 , _snake_case=4 , _snake_case=None , _snake_case=1000 , ) -> Any: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = text_seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = coordinate_size UpperCAmelCase = shape_size UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) UpperCAmelCase = text_seq_length UpperCAmelCase = (image_size // patch_size) ** 2 + 1 UpperCAmelCase = self.text_seq_length + self.image_seq_length def snake_case_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase = bbox[i, j, 3] UpperCAmelCase = bbox[i, j, 1] UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase = bbox[i, j, 2] UpperCAmelCase = bbox[i, j, 0] UpperCAmelCase = t UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) UpperCAmelCase = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def snake_case_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> Any: """simple docstring""" UpperCAmelCase = LayoutLMvaModel(config=_snake_case ) model.to(_snake_case ) model.eval() # text + image UpperCAmelCase = model(_snake_case , pixel_values=_snake_case ) UpperCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) UpperCAmelCase = model(_snake_case , bbox=_snake_case , pixel_values=_snake_case , token_type_ids=_snake_case ) UpperCAmelCase = model(_snake_case , bbox=_snake_case , pixel_values=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only UpperCAmelCase = model(_snake_case ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only UpperCAmelCase = model(pixel_values=_snake_case ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def snake_case_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> str: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = LayoutLMvaForSequenceClassification(_snake_case ) model.to(_snake_case ) model.eval() UpperCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> str: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = LayoutLMvaForTokenClassification(config=_snake_case ) model.to(_snake_case ) model.eval() UpperCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def snake_case_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> str: """simple docstring""" UpperCAmelCase = LayoutLMvaForQuestionAnswering(config=_snake_case ) model.to(_snake_case ) model.eval() UpperCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_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 snake_case_ ( self ) -> str: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = { '''input_ids''': input_ids, '''bbox''': bbox, '''pixel_values''': pixel_values, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowercase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE = ( {"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel} if is_torch_available() else {} ) def snake_case_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> Optional[Any]: """simple docstring""" # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def snake_case_ ( self ) -> List[Any]: """simple docstring""" UpperCAmelCase = LayoutLMvaModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=_snake_case , hidden_size=37 ) def snake_case_ ( self , _snake_case , _snake_case , _snake_case=False ) -> str: """simple docstring""" UpperCAmelCase = copy.deepcopy(_snake_case ) if model_class in get_values(_snake_case ): UpperCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(_snake_case , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(_snake_case ): UpperCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) elif model_class in get_values(_snake_case ): UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) elif model_class in [ *get_values(_snake_case ), ]: UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) elif model_class in [ *get_values(_snake_case ), ]: UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=_snake_case , ) return inputs_dict def snake_case_ ( self ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() def snake_case_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase = type self.model_tester.create_and_check_model(*_snake_case ) def snake_case_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_snake_case ) def snake_case_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_snake_case ) def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_snake_case ) @slow def snake_case_ ( self ) -> Any: """simple docstring""" for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = LayoutLMvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch class lowercase ( unittest.TestCase ): '''simple docstring''' @cached_property def snake_case_ ( self ) -> Tuple: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=_snake_case ) if is_vision_available() else None @slow def snake_case_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' ).to(_snake_case ) UpperCAmelCase = self.default_image_processor UpperCAmelCase = prepare_img() UpperCAmelCase = image_processor(images=_snake_case , return_tensors='''pt''' ).pixel_values.to(_snake_case ) UpperCAmelCase = torch.tensor([[1, 2]] ) UpperCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass UpperCAmelCase = model( input_ids=input_ids.to(_snake_case ) , bbox=bbox.to(_snake_case ) , pixel_values=pixel_values.to(_snake_case ) , ) # verify the logits UpperCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , _snake_case ) UpperCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , _snake_case , atol=1e-4 ) )
254
0
"""simple docstring""" from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __lowerCamelCase ( lowerCAmelCase__ ): A__ = prime_factors(lowerCAmelCase__ ) if is_square_free(lowerCAmelCase__ ): return -1 if len(lowerCAmelCase__ ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
716
"""simple docstring""" import numpy as np def __lowerCamelCase ( lowerCAmelCase__ ): return 1 / (1 + np.exp(-vector )) def __lowerCamelCase ( lowerCAmelCase__ ): return vector * sigmoid(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
554
0
'''simple docstring''' import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class __A : def __init__(self : Optional[Any] , __a : str , __a : Union[str, Any]=13 , __a : List[Any]=7 , __a : List[str]=6 , __a : Union[str, Any]=17 , __a : List[Any]=23 , __a : Optional[int]=11 , __a : str=True , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = seq_length UpperCAmelCase_ = act_dim UpperCAmelCase_ = state_dim UpperCAmelCase_ = hidden_size UpperCAmelCase_ = max_length UpperCAmelCase_ = is_training def _lowercase (self : Tuple ): UpperCAmelCase_ = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) UpperCAmelCase_ = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) UpperCAmelCase_ = floats_tensor((self.batch_size, self.seq_length, 1) ) UpperCAmelCase_ = floats_tensor((self.batch_size, self.seq_length, 1) ) UpperCAmelCase_ = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) UpperCAmelCase_ = random_attention_mask((self.batch_size, self.seq_length) ) UpperCAmelCase_ = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def _lowercase (self : Any ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def _lowercase (self : Tuple , __a : Any , __a : str , __a : Optional[Any] , __a : Optional[int] , __a : Dict , __a : List[str] , __a : Optional[int] , ): UpperCAmelCase_ = DecisionTransformerModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , __a , __a , __a , __a , __a ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def _lowercase (self : Tuple ): UpperCAmelCase_ = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) = config_and_inputs UpperCAmelCase_ = { "states": states, "actions": actions, "rewards": rewards, "returns_to_go": returns_to_go, "timesteps": timesteps, "attention_mask": attention_mask, } return config, inputs_dict @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : str = (DecisionTransformerModel,) if is_torch_available() else () a__ : List[str] = () a__ : Optional[Any] = {"""feature-extraction""": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids a__ : Any = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features a__ : Dict = False a__ : List[str] = False a__ : List[str] = False a__ : List[Any] = False a__ : Optional[int] = False a__ : int = False a__ : Union[str, Any] = False a__ : List[str] = False a__ : List[Any] = False def _lowercase (self : Dict ): UpperCAmelCase_ = DecisionTransformerModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , hidden_size=37 ) def _lowercase (self : Optional[int] ): self.config_tester.run_common_tests() def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) @slow def _lowercase (self : Optional[Any] ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ = DecisionTransformerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ) UpperCAmelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = [ "states", "actions", "rewards", "returns_to_go", "timesteps", "attention_mask", ] self.assertListEqual(arg_names[: len(__a )] , __a ) @require_torch class __A ( unittest.TestCase ): @slow def _lowercase (self : List[Any] ): UpperCAmelCase_ = 2 # number of steps of autoregressive prediction we will perform UpperCAmelCase_ = 10 # defined by the RL environment, may be normalized UpperCAmelCase_ = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-expert" ) UpperCAmelCase_ = model.to(__a ) UpperCAmelCase_ = model.config torch.manual_seed(0 ) UpperCAmelCase_ = torch.randn(1 , 1 , config.state_dim ).to(device=__a , dtype=torch.floataa ) # env.reset() UpperCAmelCase_ = torch.tensor( [[0.24_27_93, -0.28_69_30_74, 0.8_74_26_13], [0.67_81_52_74, -0.08_10_10_85, -0.12_95_21_47]] , device=__a ) UpperCAmelCase_ = torch.tensor(__a , device=__a , dtype=torch.floataa ).reshape(1 , 1 , 1 ) UpperCAmelCase_ = state UpperCAmelCase_ = torch.zeros(1 , 0 , config.act_dim , device=__a , dtype=torch.floataa ) UpperCAmelCase_ = torch.zeros(1 , 0 , device=__a , dtype=torch.floataa ) UpperCAmelCase_ = torch.tensor(0 , device=__a , dtype=torch.long ).reshape(1 , 1 ) for step in range(__a ): UpperCAmelCase_ = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=__a )] , dim=1 ) UpperCAmelCase_ = torch.cat([rewards, torch.zeros(1 , 1 , device=__a )] , dim=1 ) UpperCAmelCase_ = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = model( states=__a , actions=__a , rewards=__a , returns_to_go=__a , timesteps=__a , attention_mask=__a , return_dict=__a , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=__a , dtype=torch.floataa ), 1.0, False, {}, ) UpperCAmelCase_ = action_pred[0, -1] UpperCAmelCase_ = torch.cat([states, state] , dim=1 ) UpperCAmelCase_ = returns_to_go[0, -1] - reward UpperCAmelCase_ = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) UpperCAmelCase_ = torch.cat( [timesteps, torch.ones((1, 1) , device=__a , dtype=torch.long ) * (step + 1)] , dim=1 )
78
"""simple docstring""" import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowercase_ ( a_ , a_ ): @register_to_config def __init__( self : Any , _lowercase : int = 1_2_8 , _lowercase : int = 2_5_6 , _lowercase : float = 2000.0 , _lowercase : int = 7_6_8 , _lowercase : int = 1_2 , _lowercase : int = 1_2 , _lowercase : int = 6_4 , _lowercase : int = 2_0_4_8 , _lowercase : float = 0.1 , ): super().__init__() lowerCAmelCase__ : Optional[int] = nn.Sequential( nn.Linear(_lowercase , d_model * 4 , bias=_lowercase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=_lowercase ) , nn.SiLU() , ) lowerCAmelCase__ : Dict = nn.Embedding(_lowercase , _lowercase ) lowerCAmelCase__ : str = False lowerCAmelCase__ : str = nn.Linear(_lowercase , _lowercase , bias=_lowercase ) lowerCAmelCase__ : Any = nn.Dropout(p=_lowercase ) lowerCAmelCase__ : Optional[int] = nn.ModuleList() for lyr_num in range(_lowercase ): # FiLM conditional T5 decoder lowerCAmelCase__ : List[str] = DecoderLayer(d_model=_lowercase , d_kv=_lowercase , num_heads=_lowercase , d_ff=_lowercase , dropout_rate=_lowercase ) self.decoders.append(_lowercase ) lowerCAmelCase__ : Dict = TaLayerNorm(_lowercase ) lowerCAmelCase__ : Tuple = nn.Dropout(p=_lowercase ) lowerCAmelCase__ : int = nn.Linear(_lowercase , _lowercase , bias=_lowercase ) def _lowerCAmelCase ( self : Dict , _lowercase : List[Any] , _lowercase : Union[str, Any] ): lowerCAmelCase__ : str = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def _lowerCAmelCase ( self : Union[str, Any] , _lowercase : int , _lowercase : Dict , _lowercase : List[Any] ): lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : Dict = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. lowerCAmelCase__ : Tuple = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) lowerCAmelCase__ : Union[str, Any] = self.conditioning_emb(_lowercase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) lowerCAmelCase__ : Optional[Any] = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. lowerCAmelCase__ : Union[str, Any] = torch.broadcast_to( torch.arange(_lowercase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) lowerCAmelCase__ : List[Any] = self.position_encoding(_lowercase ) lowerCAmelCase__ : List[str] = self.continuous_inputs_projection(_lowercase ) inputs += position_encodings lowerCAmelCase__ : Optional[Any] = self.dropout(_lowercase ) # decoder: No padding present. lowerCAmelCase__ : int = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. lowerCAmelCase__ : List[Any] = [(x, self.encoder_decoder_mask(_lowercase , _lowercase )) for x, y in encodings_and_masks] # cross attend style: concat encodings lowerCAmelCase__ : Union[str, Any] = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) lowerCAmelCase__ : Any = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: lowerCAmelCase__ : Optional[int] = lyr( _lowercase , conditioning_emb=_lowercase , encoder_hidden_states=_lowercase , encoder_attention_mask=_lowercase , )[0] lowerCAmelCase__ : int = self.decoder_norm(_lowercase ) lowerCAmelCase__ : Union[str, Any] = self.post_dropout(_lowercase ) lowerCAmelCase__ : Union[str, Any] = self.spec_out(_lowercase ) return spec_out class lowercase_ ( nn.Module ): def __init__( self : Any , _lowercase : Tuple , _lowercase : List[str] , _lowercase : List[str] , _lowercase : List[Any] , _lowercase : Optional[int] , _lowercase : Tuple=1e-6 ): super().__init__() lowerCAmelCase__ : Any = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=_lowercase , d_kv=_lowercase , num_heads=_lowercase , dropout_rate=_lowercase ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=_lowercase , d_kv=_lowercase , num_heads=_lowercase , dropout_rate=_lowercase , layer_norm_epsilon=_lowercase , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=_lowercase , d_ff=_lowercase , dropout_rate=_lowercase , layer_norm_epsilon=_lowercase ) ) def _lowerCAmelCase ( self : int , _lowercase : int , _lowercase : Any=None , _lowercase : List[Any]=None , _lowercase : Any=None , _lowercase : Tuple=None , _lowercase : str=None , ): lowerCAmelCase__ : Tuple = self.layer[0]( _lowercase , conditioning_emb=_lowercase , attention_mask=_lowercase , ) if encoder_hidden_states is not None: lowerCAmelCase__ : Any = torch.where(encoder_attention_mask > 0 , 0 , -1e1_0 ).to( encoder_hidden_states.dtype ) lowerCAmelCase__ : Optional[int] = self.layer[1]( _lowercase , key_value_states=_lowercase , attention_mask=_lowercase , ) # Apply Film Conditional Feed Forward layer lowerCAmelCase__ : Tuple = self.layer[-1](_lowercase , _lowercase ) return (hidden_states,) class lowercase_ ( nn.Module ): def __init__( self : List[Any] , _lowercase : int , _lowercase : List[Any] , _lowercase : Any , _lowercase : Union[str, Any] ): super().__init__() lowerCAmelCase__ : Dict = TaLayerNorm(_lowercase ) lowerCAmelCase__ : int = TaFiLMLayer(in_features=d_model * 4 , out_features=_lowercase ) lowerCAmelCase__ : List[str] = Attention(query_dim=_lowercase , heads=_lowercase , dim_head=_lowercase , out_bias=_lowercase , scale_qk=_lowercase ) lowerCAmelCase__ : Optional[int] = nn.Dropout(_lowercase ) def _lowerCAmelCase ( self : Any , _lowercase : Dict , _lowercase : Any=None , _lowercase : Union[str, Any]=None , ): # pre_self_attention_layer_norm lowerCAmelCase__ : List[str] = self.layer_norm(_lowercase ) if conditioning_emb is not None: lowerCAmelCase__ : str = self.FiLMLayer(_lowercase , _lowercase ) # Self-attention block lowerCAmelCase__ : str = self.attention(_lowercase ) lowerCAmelCase__ : str = hidden_states + self.dropout(_lowercase ) return hidden_states class lowercase_ ( nn.Module ): def __init__( self : Optional[int] , _lowercase : Optional[int] , _lowercase : Dict , _lowercase : Optional[int] , _lowercase : Union[str, Any] , _lowercase : Tuple ): super().__init__() lowerCAmelCase__ : Any = Attention(query_dim=_lowercase , heads=_lowercase , dim_head=_lowercase , out_bias=_lowercase , scale_qk=_lowercase ) lowerCAmelCase__ : List[Any] = TaLayerNorm(_lowercase , eps=_lowercase ) lowerCAmelCase__ : Optional[Any] = nn.Dropout(_lowercase ) def _lowerCAmelCase ( self : Any , _lowercase : Tuple , _lowercase : List[Any]=None , _lowercase : List[str]=None , ): lowerCAmelCase__ : Any = self.layer_norm(_lowercase ) lowerCAmelCase__ : List[Any] = self.attention( _lowercase , encoder_hidden_states=_lowercase , attention_mask=attention_mask.squeeze(1 ) , ) lowerCAmelCase__ : List[Any] = hidden_states + self.dropout(_lowercase ) return layer_output class lowercase_ ( nn.Module ): def __init__( self : Optional[int] , _lowercase : int , _lowercase : Union[str, Any] , _lowercase : List[str] , _lowercase : Any ): super().__init__() lowerCAmelCase__ : Dict = TaDenseGatedActDense(d_model=_lowercase , d_ff=_lowercase , dropout_rate=_lowercase ) lowerCAmelCase__ : Optional[int] = TaFiLMLayer(in_features=d_model * 4 , out_features=_lowercase ) lowerCAmelCase__ : str = TaLayerNorm(_lowercase , eps=_lowercase ) lowerCAmelCase__ : Optional[Any] = nn.Dropout(_lowercase ) def _lowerCAmelCase ( self : Union[str, Any] , _lowercase : Tuple , _lowercase : List[str]=None ): lowerCAmelCase__ : Union[str, Any] = self.layer_norm(_lowercase ) if conditioning_emb is not None: lowerCAmelCase__ : int = self.film(_lowercase , _lowercase ) lowerCAmelCase__ : str = self.DenseReluDense(_lowercase ) lowerCAmelCase__ : Optional[int] = hidden_states + self.dropout(_lowercase ) return hidden_states class lowercase_ ( nn.Module ): def __init__( self : Tuple , _lowercase : int , _lowercase : List[str] , _lowercase : Optional[int] ): super().__init__() lowerCAmelCase__ : Union[str, Any] = nn.Linear(_lowercase , _lowercase , bias=_lowercase ) lowerCAmelCase__ : List[Any] = nn.Linear(_lowercase , _lowercase , bias=_lowercase ) lowerCAmelCase__ : str = nn.Linear(_lowercase , _lowercase , bias=_lowercase ) lowerCAmelCase__ : Union[str, Any] = nn.Dropout(_lowercase ) lowerCAmelCase__ : Tuple = NewGELUActivation() def _lowerCAmelCase ( self : Tuple , _lowercase : Any ): lowerCAmelCase__ : Union[str, Any] = self.act(self.wi_a(_lowercase ) ) lowerCAmelCase__ : Optional[Any] = self.wi_a(_lowercase ) lowerCAmelCase__ : Optional[Any] = hidden_gelu * hidden_linear lowerCAmelCase__ : Optional[int] = self.dropout(_lowercase ) lowerCAmelCase__ : int = self.wo(_lowercase ) return hidden_states class lowercase_ ( nn.Module ): def __init__( self : Any , _lowercase : int , _lowercase : int=1e-6 ): super().__init__() lowerCAmelCase__ : Optional[Any] = nn.Parameter(torch.ones(_lowercase ) ) lowerCAmelCase__ : Union[str, Any] = eps def _lowerCAmelCase ( self : Dict , _lowercase : str ): # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 lowerCAmelCase__ : str = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=_lowercase ) lowerCAmelCase__ : Tuple = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: lowerCAmelCase__ : int = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class lowercase_ ( nn.Module ): def _lowerCAmelCase ( self : Union[str, Any] , _lowercase : torch.Tensor ): return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(_lowercase , 3.0 )) )) class lowercase_ ( nn.Module ): def __init__( self : Tuple , _lowercase : int , _lowercase : Optional[int] ): super().__init__() lowerCAmelCase__ : Dict = nn.Linear(_lowercase , out_features * 2 , bias=_lowercase ) def _lowerCAmelCase ( self : str , _lowercase : List[Any] , _lowercase : Dict ): lowerCAmelCase__ : Tuple = self.scale_bias(_lowercase ) lowerCAmelCase__ , lowerCAmelCase__ : Any = torch.chunk(_lowercase , 2 , -1 ) lowerCAmelCase__ : List[Any] = x * (1 + scale) + shift return x
308
0
"""simple docstring""" import argparse from collections import defaultdict def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase_ = f"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(lowerCAmelCase__ , "r" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = f"""class {class_name}(""" UpperCAmelCase_ = f"""{4 * ' '}def {test_name}(""" UpperCAmelCase_ = f"""{8 * ' '}{correct_line.split()[0]}""" UpperCAmelCase_ = f"""{16 * ' '}{correct_line.split()[0]}""" UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 UpperCAmelCase_ = [] for line in lines: if line.startswith(lowerCAmelCase__ ): UpperCAmelCase_ = True elif in_class and line.startswith(lowerCAmelCase__ ): UpperCAmelCase_ = True elif in_class and in_func and (line.startswith(lowerCAmelCase__ ) or line.startswith(lowerCAmelCase__ )): UpperCAmelCase_ = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: UpperCAmelCase_ = True if in_class and in_func and in_line: if ")" not in line: continue else: UpperCAmelCase_ = True if in_class and in_func and in_line and insert_line: new_lines.append(f"""{spaces * ' '}{correct_line}""" ) UpperCAmelCase_ = UpperCAmelCase_ = UpperCAmelCase_ = UpperCAmelCase_ = False else: new_lines.append(lowerCAmelCase__ ) with open(lowerCAmelCase__ , "w" ) as f: for line in new_lines: f.write(lowerCAmelCase__ ) def a__ ( lowerCAmelCase__ , lowerCAmelCase__=None ): if fail is not None: with open(lowerCAmelCase__ , "r" ) as f: UpperCAmelCase_ = {l.strip() for l in f.readlines()} else: UpperCAmelCase_ = None with open(lowerCAmelCase__ , "r" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = defaultdict(lowerCAmelCase__ ) for line in correct_lines: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = line.split(";" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--correct_filename""", help="""filename of tests with expected result""") parser.add_argument("""--fail_filename""", help="""filename of test failures""", type=str, default=None) lowerCamelCase = parser.parse_args() main(args.correct_filename, args.fail_filename)
14
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCamelCase = logging.get_logger(__name__) def a__ ( lowerCAmelCase__ ): if isinstance(lowerCAmelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase__ ): return [[videos]] raise ValueError(f"""Could not make batched video from {videos}""" ) class lowercase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = ['''pixel_values'''] def __init__( self : Tuple , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 255 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , **_UpperCAmelCase : Any , ) -> None: '''simple docstring''' super().__init__(**_UpperCAmelCase ) UpperCAmelCase_ = size if size is not None else {"shortest_edge": 224} UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) UpperCAmelCase_ = crop_size if crop_size is not None else {"height": 224, "width": 224} UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , param_name="crop_size" ) UpperCAmelCase_ = do_resize UpperCAmelCase_ = size UpperCAmelCase_ = do_center_crop UpperCAmelCase_ = crop_size UpperCAmelCase_ = resample UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_normalize UpperCAmelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowercase__ ( self : Tuple , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Tuple , ) -> np.ndarray: '''simple docstring''' UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) if "shortest_edge" in size: UpperCAmelCase_ = get_resize_output_image_size(_UpperCAmelCase , size["shortest_edge"] , default_to_square=_UpperCAmelCase ) elif "height" in size and "width" in size: UpperCAmelCase_ = (size["height"], size["width"]) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : Union[str, Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Union[str, Any] , ) -> np.ndarray: '''simple docstring''' UpperCAmelCase_ = get_size_dict(_UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(_UpperCAmelCase , size=(size["height"], size["width"]) , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : List[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : str , ) -> List[str]: '''simple docstring''' return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : Optional[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Tuple , ) -> np.ndarray: '''simple docstring''' return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : Any , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop 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("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = to_numpy_array(_UpperCAmelCase ) if do_resize: UpperCAmelCase_ = self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase ) if do_center_crop: UpperCAmelCase_ = self.center_crop(_UpperCAmelCase , size=_UpperCAmelCase ) if do_rescale: UpperCAmelCase_ = self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase ) if do_normalize: UpperCAmelCase_ = self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase ) UpperCAmelCase_ = to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase ) return image def lowercase__ ( self : Optional[Any] , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCAmelCase : int , ) -> PIL.Image.Image: '''simple docstring''' UpperCAmelCase_ = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ = resample if resample is not None else self.resample UpperCAmelCase_ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase_ = image_mean if image_mean is not None else self.image_mean UpperCAmelCase_ = image_std if image_std is not None else self.image_std UpperCAmelCase_ = size if size is not None else self.size UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase ) UpperCAmelCase_ = crop_size if crop_size is not None else self.crop_size UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , param_name="crop_size" ) if not valid_images(_UpperCAmelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) UpperCAmelCase_ = make_batched(_UpperCAmelCase ) UpperCAmelCase_ = [ [ self._preprocess_image( image=_UpperCAmelCase , do_resize=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , do_center_crop=_UpperCAmelCase , crop_size=_UpperCAmelCase , do_rescale=_UpperCAmelCase , rescale_factor=_UpperCAmelCase , do_normalize=_UpperCAmelCase , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase , data_format=_UpperCAmelCase , ) for img in video ] for video in videos ] UpperCAmelCase_ = {"pixel_values": videos} return BatchFeature(data=_UpperCAmelCase , tensor_type=_UpperCAmelCase )
14
1
'''simple docstring''' import argparse from collections import defaultdict import yaml UpperCAmelCase_ : int = '''docs/source/en/_toctree.yml''' def _UpperCamelCase (_lowerCamelCase : Tuple )-> List[str]: '''simple docstring''' __snake_case = defaultdict(_lowerCamelCase ) __snake_case = [] __snake_case = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'''local''': doc['''local'''], '''title''': doc['''title''']} ) else: new_doc_list.append(_lowerCamelCase ) __snake_case = new_doc_list __snake_case = [key for key, value in counts.items() if value > 1] __snake_case = [] for duplicate_key in duplicates: __snake_case = list({doc['''title'''] for doc in doc_list if doc['''local'''] == duplicate_key} ) if len(_lowerCamelCase ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if '''local''' not in counts or counts[doc['''local''']] == 1] ) __snake_case = sorted(_lowerCamelCase , key=lambda _lowerCamelCase : s["title"].lower() ) # "overview" gets special treatment and is always first if len(_lowerCamelCase ) > 1: raise ValueError('''{doc_list} has two \'overview\' docs which is not allowed.''' ) overview_doc.extend(_lowerCamelCase ) # Sort return overview_doc def _UpperCamelCase (_lowerCamelCase : Tuple=False )-> Any: '''simple docstring''' with open(_lowerCamelCase , encoding='''utf-8''' ) as f: __snake_case = yaml.safe_load(f.read() ) # Get to the API doc __snake_case = 0 while content[api_idx]["title"] != "API": api_idx += 1 __snake_case = content[api_idx]['''sections'''] # Then to the model doc __snake_case = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 __snake_case = api_doc[scheduler_idx]['''sections'''] __snake_case = clean_doc_toc(_lowerCamelCase ) __snake_case = False if new_scheduler_doc != scheduler_doc: __snake_case = True if overwrite: __snake_case = new_scheduler_doc if diff: if overwrite: __snake_case = api_doc with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(_lowerCamelCase , allow_unicode=_lowerCamelCase ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) def _UpperCamelCase (_lowerCamelCase : int=False )-> Optional[int]: '''simple docstring''' with open(_lowerCamelCase , encoding='''utf-8''' ) as f: __snake_case = yaml.safe_load(f.read() ) # Get to the API doc __snake_case = 0 while content[api_idx]["title"] != "API": api_idx += 1 __snake_case = content[api_idx]['''sections'''] # Then to the model doc __snake_case = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 __snake_case = False __snake_case = api_doc[pipeline_idx]['''sections'''] __snake_case = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: __snake_case = pipeline_doc['''section'''] __snake_case = clean_doc_toc(_lowerCamelCase ) if overwrite: __snake_case = new_sub_pipeline_doc new_pipeline_docs.append(_lowerCamelCase ) # sort overall pipeline doc __snake_case = clean_doc_toc(_lowerCamelCase ) if new_pipeline_docs != pipeline_docs: __snake_case = True if overwrite: __snake_case = new_pipeline_docs if diff: if overwrite: __snake_case = api_doc with open(_lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(_lowerCamelCase , allow_unicode=_lowerCamelCase ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') UpperCAmelCase_ : Dict = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
24
def _lowercase ( __UpperCamelCase : Any , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[Any] , __UpperCamelCase : List[Any] ): if height >= 1: move_tower(height - 1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) move_disk(__UpperCamelCase , __UpperCamelCase ) move_tower(height - 1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def _lowercase ( __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int] ): print("""moving disk from""" , __UpperCamelCase , """to""" , __UpperCamelCase ) def _lowercase ( ): snake_case__ = int(input("""Height of hanoi: """ ).strip() ) move_tower(__UpperCamelCase , """A""" , """B""" , """C""" ) if __name__ == "__main__": main()
214
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): """simple docstring""" __A : str = tempfile.mkdtemp() __A : str = SamImageProcessor() __A : List[str] = SamProcessor(__lowercase ) processor.save_pretrained(self.tmpdirname ) def snake_case__ ( self , **__lowercase ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__lowercase ).image_processor def snake_case__ ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def snake_case__ ( self ): """simple docstring""" __A : Union[str, Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Any = [Image.fromarray(np.moveaxis(__lowercase , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case__ ( self ): """simple docstring""" __A : int = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Dict = self.get_image_processor(do_normalize=__lowercase , padding_value=1.0 ) __A : Union[str, Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=__lowercase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowercase ) def snake_case__ ( self ): """simple docstring""" __A : Optional[Any] = self.get_image_processor() __A : Any = SamProcessor(image_processor=__lowercase ) __A : List[str] = self.prepare_image_inputs() __A : List[str] = image_processor(__lowercase , return_tensors='np' ) __A : Any = processor(images=__lowercase , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def snake_case__ ( self ): """simple docstring""" __A : Optional[int] = self.get_image_processor() __A : List[Any] = SamProcessor(image_processor=__lowercase ) __A : str = [torch.ones((1, 3, 5, 5) )] __A : List[Any] = [[1_764, 2_646]] __A : List[str] = [[683, 1_024]] __A : Optional[int] = processor.post_process_masks(__lowercase , __lowercase , __lowercase ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) __A : Union[str, Any] = processor.post_process_masks( __lowercase , torch.tensor(__lowercase ) , torch.tensor(__lowercase ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np __A : Optional[Any] = [np.ones((1, 3, 5, 5) )] __A : List[Any] = processor.post_process_masks(__lowercase , np.array(__lowercase ) , np.array(__lowercase ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) __A : Union[str, Any] = [[1, 0], [0, 1]] with self.assertRaises(__lowercase ): __A : Dict = processor.post_process_masks(__lowercase , np.array(__lowercase ) , np.array(__lowercase ) ) @require_vision @require_tf class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): """simple docstring""" __A : str = tempfile.mkdtemp() __A : Tuple = SamImageProcessor() __A : Dict = SamProcessor(__lowercase ) processor.save_pretrained(self.tmpdirname ) def snake_case__ ( self , **__lowercase ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__lowercase ).image_processor def snake_case__ ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def snake_case__ ( self ): """simple docstring""" __A : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Union[str, Any] = [Image.fromarray(np.moveaxis(__lowercase , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case__ ( self ): """simple docstring""" __A : str = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : List[Any] = self.get_image_processor(do_normalize=__lowercase , padding_value=1.0 ) __A : Dict = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=__lowercase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowercase ) def snake_case__ ( self ): """simple docstring""" __A : str = self.get_image_processor() __A : List[str] = SamProcessor(image_processor=__lowercase ) __A : Tuple = self.prepare_image_inputs() __A : str = image_processor(__lowercase , return_tensors='np' ) __A : Union[str, Any] = processor(images=__lowercase , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def snake_case__ ( self ): """simple docstring""" __A : Tuple = self.get_image_processor() __A : Any = SamProcessor(image_processor=__lowercase ) __A : int = [tf.ones((1, 3, 5, 5) )] __A : str = [[1_764, 2_646]] __A : Optional[int] = [[683, 1_024]] __A : int = processor.post_process_masks(__lowercase , __lowercase , __lowercase , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) __A : Any = processor.post_process_masks( __lowercase , tf.convert_to_tensor(__lowercase ) , tf.convert_to_tensor(__lowercase ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np __A : List[str] = [np.ones((1, 3, 5, 5) )] __A : Dict = processor.post_process_masks( __lowercase , np.array(__lowercase ) , np.array(__lowercase ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) __A : Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __A : Optional[int] = processor.post_process_masks( __lowercase , np.array(__lowercase ) , np.array(__lowercase ) , return_tensors='tf' ) @require_vision @require_torchvision class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): """simple docstring""" __A : str = tempfile.mkdtemp() __A : Tuple = SamImageProcessor() __A : int = SamProcessor(__lowercase ) processor.save_pretrained(self.tmpdirname ) def snake_case__ ( self , **__lowercase ): """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__lowercase ).image_processor def snake_case__ ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def snake_case__ ( self ): """simple docstring""" __A : Union[str, Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : List[str] = [Image.fromarray(np.moveaxis(__lowercase , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def snake_case__ ( self ): """simple docstring""" __A : int = self.get_image_processor() __A : List[Any] = SamProcessor(image_processor=__lowercase ) __A : Optional[int] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __A : Dict = [tf.convert_to_tensor(__lowercase )] __A : Optional[Any] = [torch.tensor(__lowercase )] __A : int = [[1_764, 2_646]] __A : Tuple = [[683, 1_024]] __A : Optional[int] = processor.post_process_masks( __lowercase , __lowercase , __lowercase , return_tensors='tf' ) __A : Tuple = processor.post_process_masks( __lowercase , __lowercase , __lowercase , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def snake_case__ ( self ): """simple docstring""" __A : Dict = self.get_image_processor() __A : Optional[int] = SamProcessor(image_processor=__lowercase ) __A : Optional[Any] = self.prepare_image_inputs() __A : List[str] = image_processor(__lowercase , return_tensors='pt' )['pixel_values'].numpy() __A : Dict = processor(images=__lowercase , return_tensors='pt' )['pixel_values'].numpy() __A : Tuple = image_processor(__lowercase , return_tensors='tf' )['pixel_values'].numpy() __A : Union[str, Any] = processor(images=__lowercase , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(__lowercase , __lowercase ) ) self.assertTrue(np.allclose(__lowercase , __lowercase ) ) self.assertTrue(np.allclose(__lowercase , __lowercase ) )
540
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def snake_case__ ( self ): """simple docstring""" torch.manual_seed(0 ) __A : Optional[int] = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def snake_case__ ( self ): """simple docstring""" torch.manual_seed(0 ) __A : Dict = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def snake_case__ ( self ): """simple docstring""" torch.manual_seed(0 ) __A : Union[str, Any] = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) __A : Union[str, Any] = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def snake_case__ ( self ): """simple docstring""" __A : str = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : int = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __A : Tuple = DDPMScheduler() __A : Optional[int] = AudioDiffusionPipeline(vqvae=__lowercase , unet=self.dummy_unet , mel=__lowercase , scheduler=__lowercase ) __A : Dict = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __A : Tuple = torch.Generator(device=__lowercase ).manual_seed(42 ) __A : Tuple = pipe(generator=__lowercase , steps=4 ) __A : Union[str, Any] = output.audios[0] __A : Dict = output.images[0] __A : Optional[Any] = torch.Generator(device=__lowercase ).manual_seed(42 ) __A : Optional[int] = pipe(generator=__lowercase , steps=4 , return_dict=__lowercase ) __A : int = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __A : Optional[int] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] __A : List[Any] = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] __A : Optional[Any] = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __A : Optional[int] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __A : Optional[Any] = DDIMScheduler() __A : List[Any] = self.dummy_vqvae_and_unet __A : int = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=__lowercase , scheduler=__lowercase ) __A : Dict = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) np.random.seed(0 ) __A : Dict = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __A : Dict = torch.Generator(device=__lowercase ).manual_seed(42 ) __A : List[Any] = pipe(raw_audio=__lowercase , generator=__lowercase , start_step=5 , steps=10 ) __A : Tuple = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __A : int = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] __A : List[str] = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __A : Any = self.dummy_unet_condition __A : Optional[int] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=__lowercase , mel=__lowercase , scheduler=__lowercase ) __A : Union[str, Any] = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) np.random.seed(0 ) __A : Dict = torch.rand((1, 1, 10) ) __A : Any = pipe(generator=__lowercase , encoding=__lowercase ) __A : Union[str, Any] = output.images[0] __A : List[Any] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] __A : int = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self ): """simple docstring""" __A : Union[str, Any] = torch_device __A : Union[str, Any] = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) __A : Dict = pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) __A : Any = torch.Generator(device=__lowercase ).manual_seed(42 ) __A : Optional[Any] = pipe(generator=__lowercase ) __A : Union[str, Any] = output.audios[0] __A : List[Any] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __A : Union[str, Any] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] __A : Optional[Any] = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
540
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase_ : Tuple = logging.get_logger(__name__) lowerCAmelCase_ : List[Any] = { 'google/umt5-small': 'https://huggingface.co/google/umt5-small/resolve/main/config.json', # See all umt5 models at https://huggingface.co/models?filter=umt5 } class __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): """simple docstring""" __a ='umt5' __a =['past_key_values'] def __init__( self : int , __a : int=25_01_12 , __a : Dict=5_12 , __a : List[Any]=64 , __a : List[Any]=10_24 , __a : Tuple=8 , __a : Union[str, Any]=None , __a : int=6 , __a : List[str]=32 , __a : str=1_28 , __a : List[Any]=0.1 , __a : Tuple=1e-6 , __a : Optional[Any]=1.0 , __a : str="gated-gelu" , __a : Dict=True , __a : Optional[int]=True , __a : List[str]="T5Tokenizer" , __a : str=True , __a : List[str]=0 , __a : Union[str, Any]=1 , __a : Any=0 , **__a : List[Any] , ): super().__init__( is_encoder_decoder=_lowercase , tokenizer_class=_lowercase , tie_word_embeddings=_lowercase , pad_token_id=_lowercase , eos_token_id=_lowercase , decoder_start_token_id=_lowercase , **_lowercase , ) _a = vocab_size _a = d_model _a = d_kv _a = d_ff _a = num_layers _a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _a = num_heads _a = relative_attention_num_buckets _a = relative_attention_max_distance _a = dropout_rate _a = layer_norm_epsilon _a = initializer_factor _a = feed_forward_proj _a = use_cache _a = self.feed_forward_proj.split("-" ) _a = act_info[-1] _a = act_info[0] == "gated" if len(_lowercase ) > 1 and act_info[0] != "gated" or len(_lowercase ) > 2: raise ValueError( f'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": _a = "gelu_new" @property def UpperCamelCase__ ( self : Dict ): return self.d_model @property def UpperCamelCase__ ( self : str ): return self.num_heads @property def UpperCamelCase__ ( self : Union[str, Any] ): return self.num_layers class __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): """simple docstring""" @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def UpperCamelCase__ ( self : Any ): _a = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: _a = "past_encoder_sequence + sequence" _a = {0: "batch"} _a = {0: "batch", 1: "past_decoder_sequence + sequence"} else: _a = {0: "batch", 1: "decoder_sequence"} _a = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(_lowercase , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def UpperCamelCase__ ( self : List[str] ): return 13 @property def UpperCamelCase__ ( self : int ): return 5e-4
692
"""simple docstring""" import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[str] , lowerCamelCase_: List[Any]=False ): """simple docstring""" try: snake_case : Optional[int] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. snake_case : List[Any] = default else: # KEY is set, convert it to True or False. try: snake_case : Dict = strtobool(lowerCamelCase_ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f'''If set, {key} must be yes or no.''' ) return _value A = parse_flag_from_env('RUN_SLOW', default=False) A = parse_flag_from_env('RUN_REMOTE', default=False) A = parse_flag_from_env('RUN_LOCAL', default=True) A = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression A = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') A = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') A = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio A = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam A = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility A = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows A = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[Any] ): """simple docstring""" try: import faiss # noqa except ImportError: snake_case : Dict = unittest.skip("test requires faiss" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Any ): """simple docstring""" try: import regex # noqa except ImportError: snake_case : List[Any] = unittest.skip("test requires regex" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: int ): """simple docstring""" try: import elasticsearch # noqa except ImportError: snake_case : Tuple = unittest.skip("test requires elasticsearch" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Any ): """simple docstring""" try: import sqlalchemy # noqa except ImportError: snake_case : Dict = unittest.skip("test requires sqlalchemy" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[Any] ): """simple docstring""" if not config.TORCH_AVAILABLE: snake_case : Dict = unittest.skip("test requires PyTorch" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[Any] ): """simple docstring""" if not config.TF_AVAILABLE: snake_case : Tuple = unittest.skip("test requires TensorFlow" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[str] ): """simple docstring""" if not config.JAX_AVAILABLE: snake_case : str = unittest.skip("test requires JAX" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Any ): """simple docstring""" if not config.PIL_AVAILABLE: snake_case : Union[str, Any] = unittest.skip("test requires Pillow" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Union[str, Any] ): """simple docstring""" try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers" )(lowerCamelCase_ ) else: return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Dict ): """simple docstring""" try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken" )(lowerCamelCase_ ) else: return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[str] ): """simple docstring""" try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy" )(lowerCamelCase_ ) else: return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: str ): """simple docstring""" def _require_spacy_model(lowerCamelCase_: Dict ): try: import spacy # noqa F401 spacy.load(lowerCamelCase_ ) except ImportError: return unittest.skip("test requires spacy" )(lowerCamelCase_ ) except OSError: return unittest.skip("test requires spacy model '{}'".format(lowerCamelCase_ ) )(lowerCamelCase_ ) else: return test_case return _require_spacy_model def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Dict ): """simple docstring""" try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark" )(lowerCamelCase_ ) else: return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[Any] ): """simple docstring""" try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark" )(lowerCamelCase_ ) else: return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[Any] ): """simple docstring""" if not _run_slow_tests or _run_slow_tests == 0: snake_case : Dict = unittest.skip("test is slow" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Any ): """simple docstring""" if not _run_local_tests or _run_local_tests == 0: snake_case : int = unittest.skip("test is local" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Dict ): """simple docstring""" if not _run_packaged_tests or _run_packaged_tests == 0: snake_case : List[str] = unittest.skip("test is packaged" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[int] ): """simple docstring""" if not _run_remote_tests or _run_remote_tests == 0: snake_case : Union[str, Any] = unittest.skip("test requires remote" )(lowerCamelCase_ ) return test_case def __SCREAMING_SNAKE_CASE ( *lowerCamelCase_: Union[str, Any] ): """simple docstring""" def decorate(cls: int ): for name, fn in cls.__dict__.items(): if callable(lowerCamelCase_ ) and name.startswith("test" ): for decorator in decorators: snake_case : Optional[Any] = decorator(lowerCamelCase_ ) setattr(cls , lowerCamelCase_ , lowerCamelCase_ ) return cls return decorate class _a ( SCREAMING_SNAKE_CASE__): pass class _a ( SCREAMING_SNAKE_CASE__): __magic_name__ = 0 __magic_name__ = 1 __magic_name__ = 2 @contextmanager def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: int=OfflineSimulationMode.CONNECTION_FAILS , lowerCamelCase_: Dict=1e-16 ): """simple docstring""" snake_case : Union[str, Any] = requests.Session().request def timeout_request(lowerCamelCase_: Tuple , lowerCamelCase_: List[Any] , lowerCamelCase_: str , **lowerCamelCase_: List[Any] ): # Change the url to an invalid url so that the connection hangs snake_case : Optional[int] = "https://10.255.255.1" if kwargs.get("timeout" ) is None: raise RequestWouldHangIndefinitelyError( f'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.''' ) snake_case : str = timeout try: return online_request(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier snake_case : Dict = url snake_case : Union[str, Any] = e.args[0] snake_case : Any = (max_retry_error.args[0].replace("10.255.255.1" , f'''OfflineMock[{url}]''' ),) snake_case : List[Any] = (max_retry_error,) raise def raise_connection_error(lowerCamelCase_: Tuple , lowerCamelCase_: str , **lowerCamelCase_: int ): raise requests.ConnectionError("Offline mode is enabled." , request=lowerCamelCase_ ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send" , lowerCamelCase_ ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request" , lowerCamelCase_ ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE" , lowerCamelCase_ ): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum." ) @contextmanager def __SCREAMING_SNAKE_CASE ( *lowerCamelCase_: List[str] , **lowerCamelCase_: Any ): """simple docstring""" snake_case : Any = str(Path().resolve() ) with tempfile.TemporaryDirectory(*lowerCamelCase_ , **lowerCamelCase_ ) as tmp_dir: try: os.chdir(lowerCamelCase_ ) yield finally: os.chdir(lowerCamelCase_ ) @contextmanager def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" import gc gc.collect() snake_case : Tuple = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" import gc gc.collect() snake_case : Optional[int] = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Tuple , lowerCamelCase_: Dict ): """simple docstring""" return deepcopy(lowerCamelCase_ ).integers(0 , 1_0_0 , 1_0 ).tolist() == deepcopy(lowerCamelCase_ ).integers(0 , 1_0_0 , 1_0 ).tolist() def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: List[Any] ): """simple docstring""" import decorator from requests.exceptions import HTTPError def _wrapper(lowerCamelCase_: Dict , *lowerCamelCase_: Tuple , **lowerCamelCase_: Any ): try: return func(*lowerCamelCase_ , **lowerCamelCase_ ) except HTTPError as err: if str(lowerCamelCase_ ).startswith("500" ) or str(lowerCamelCase_ ).startswith("502" ): pytest.xfail(str(lowerCamelCase_ ) ) raise err return decorator.decorator(_wrapper , lowerCamelCase_ ) class _a : def __init__( self : str , _lowercase : Optional[Any] , _lowercase : str , _lowercase : Optional[Any] ) -> Optional[int]: snake_case : List[Any] = returncode snake_case : Tuple = stdout snake_case : Dict = stderr async def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: str , lowerCamelCase_: Optional[Any] ): """simple docstring""" while True: snake_case : List[Any] = await stream.readline() if line: callback(lowerCamelCase_ ) else: break async def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Any , lowerCamelCase_: Dict=None , lowerCamelCase_: Union[str, Any]=None , lowerCamelCase_: int=None , lowerCamelCase_: str=False , lowerCamelCase_: Optional[Any]=False ): """simple docstring""" if echo: print("\nRunning: " , " ".join(lowerCamelCase_ ) ) snake_case : Any = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowerCamelCase_ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCamelCase_ , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) snake_case : Optional[int] = [] snake_case : Tuple = [] def tee(lowerCamelCase_: Union[str, Any] , lowerCamelCase_: str , lowerCamelCase_: Dict , lowerCamelCase_: Union[str, Any]="" ): snake_case : Optional[Any] = line.decode("utf-8" ).rstrip() sink.append(lowerCamelCase_ ) if not quiet: print(lowerCamelCase_ , lowerCamelCase_ , file=lowerCamelCase_ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda lowerCamelCase_ : tee(lowerCamelCase_ , lowerCamelCase_ , sys.stdout , label="stdout:" ) ), _read_stream(p.stderr , lambda lowerCamelCase_ : tee(lowerCamelCase_ , lowerCamelCase_ , sys.stderr , label="stderr:" ) ), ] , timeout=lowerCamelCase_ , ) return _RunOutput(await p.wait() , lowerCamelCase_ , lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( lowerCamelCase_: Optional[int] , lowerCamelCase_: Union[str, Any]=None , lowerCamelCase_: Any=None , lowerCamelCase_: List[str]=1_8_0 , lowerCamelCase_: Dict=False , lowerCamelCase_: Optional[Any]=True ): """simple docstring""" snake_case : Optional[int] = asyncio.get_event_loop() snake_case : str = loop.run_until_complete( _stream_subprocess(lowerCamelCase_ , env=lowerCamelCase_ , stdin=lowerCamelCase_ , timeout=lowerCamelCase_ , quiet=lowerCamelCase_ , echo=lowerCamelCase_ ) ) snake_case : Union[str, Any] = " ".join(lowerCamelCase_ ) if result.returncode > 0: snake_case : List[Any] = "\n".join(result.stderr ) raise RuntimeError( f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' f'''The combined stderr from workers follows:\n{stderr}''' ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f'''\'{cmd_str}\' produced no output.''' ) return result def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" snake_case : int = os.environ.get("PYTEST_XDIST_WORKER" , "gw0" ) snake_case : Dict = re.sub(r"^gw" , "" , lowerCamelCase_ , 0 , re.M ) return int(lowerCamelCase_ ) def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" snake_case : int = 2_9_5_0_0 snake_case : str = pytest_xdist_worker_id() return port + uniq_delta
449
0
def a_ ( lowerCamelCase = 5_0 ): UpperCAmelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
719
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ : Any = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class snake_case ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" snake_case__ = XLMProphetNetTokenizer snake_case__ = False snake_case__ = True def __lowerCAmelCase ( self : Any ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase__ = XLMProphetNetTokenizer(lowerCamelCase__ ,keep_accents=lowerCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Dict ): UpperCAmelCase__ = '[PAD]' UpperCAmelCase__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__ ) ,lowerCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__ ) ,lowerCamelCase__ ) def __lowerCAmelCase ( self : List[str] ): UpperCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'[PAD]' ) self.assertEqual(vocab_keys[1] ,'[CLS]' ) self.assertEqual(vocab_keys[-1] ,'j' ) self.assertEqual(len(lowerCamelCase__ ) ,1_012 ) def __lowerCAmelCase ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size ,1_012 ) def __lowerCAmelCase ( self : str ): UpperCAmelCase__ = XLMProphetNetTokenizer(lowerCamelCase__ ,keep_accents=lowerCamelCase__ ) UpperCAmelCase__ = tokenizer.tokenize('This is a test' ) self.assertListEqual(lowerCamelCase__ ,['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) ,[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] ,) UpperCAmelCase__ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowerCamelCase__ ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] ,) UpperCAmelCase__ = tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) self.assertListEqual( lowerCamelCase__ ,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] ,) UpperCAmelCase__ = tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) self.assertListEqual( lowerCamelCase__ ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '[UNK]', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '[UNK]', '.', ] ,) @cached_property def __lowerCAmelCase ( self : Dict ): return XLMProphetNetTokenizer.from_pretrained('microsoft/xprophetnet-large-wiki100-cased' ) @slow def __lowerCAmelCase ( self : Optional[Any] ): UpperCAmelCase__ = 'Hello World!' UpperCAmelCase__ = [35_389, 6_672, 49, 2] self.assertListEqual(lowerCamelCase__ ,self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def __lowerCAmelCase ( self : List[str] ): # fmt: off UpperCAmelCase__ = {'input_ids': [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase__ ,model_name='microsoft/xprophetnet-large-wiki100-cased' ,revision='1acad1643ddd54a44df6a1b797ada8373685d90e' ,)
632
0
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class lowerCAmelCase_ : """simple docstring""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Dict=3_2 , SCREAMING_SNAKE_CASE__ : str=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : List[str]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=4 , SCREAMING_SNAKE_CASE__ : str=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Dict=3_7 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=[1, 3_8_4, 2_4, 2_4] , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ): '''simple docstring''' __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __a = is_training __a = use_labels __a = hidden_size __a = num_hidden_layers __a = backbone_out_indices __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = num_labels __a = backbone_featmap_shape __a = scope __a = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def __a ( self : Tuple ): '''simple docstring''' __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_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 def __a ( self : Tuple ): '''simple docstring''' __a = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [9_6, 1_9_2, 3_8_4, 7_6_8], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE__ , backbone_featmap_shape=self.backbone_featmap_shape , ) def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ): '''simple docstring''' __a = DPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __a ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a = self.num_labels __a = DPTForDepthEstimation(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' __a = self.num_labels __a = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __a = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __a ( self : int ): '''simple docstring''' __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase_ ( snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" a_ :str =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () a_ :int =( { """depth-estimation""": DPTForDepthEstimation, """feature-extraction""": DPTModel, """image-segmentation""": DPTForSemanticSegmentation, } if is_torch_available() else {} ) a_ :Dict =False a_ :Any =False a_ :Union[str, Any] =False def __a ( self : Tuple ): '''simple docstring''' __a = DPTModelTester(self ) __a = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def __a ( self : List[Any] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def __a ( self : int ): '''simple docstring''' pass def __a ( self : Union[str, Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def __a ( self : List[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(SCREAMING_SNAKE_CASE__ ) __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] , SCREAMING_SNAKE_CASE__ ) def __a ( self : Optional[Any] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def __a ( self : Union[str, Any] ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE__ ) def __a ( self : Any ): '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__ ) def __a ( self : Any ): '''simple docstring''' for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True if model_class in get_values(SCREAMING_SNAKE_CASE__ ): continue __a = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.train() __a = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) __a = model(**SCREAMING_SNAKE_CASE__ ).loss loss.backward() def __a ( self : List[str] ): '''simple docstring''' for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = False __a = True if model_class in get_values(SCREAMING_SNAKE_CASE__ ) or not model_class.supports_gradient_checkpointing: continue __a = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.gradient_checkpointing_enable() model.train() __a = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) __a = model(**SCREAMING_SNAKE_CASE__ ).loss loss.backward() def __a ( self : Optional[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = _config_zero_init(SCREAMING_SNAKE_CASE__ ) for model_class in self.all_model_classes: __a = model_class(config=SCREAMING_SNAKE_CASE__ ) # Skip the check for the backbone __a = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": __a = [f'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue 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''' , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __a ( self : Any ): '''simple docstring''' pass @slow def __a ( self : List[str] ): '''simple docstring''' for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: __a = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def __a ( self : Optional[Any] ): '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = """add""" with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __a = DPTForDepthEstimation(SCREAMING_SNAKE_CASE__ ) def __lowercase ( ) -> List[Any]: """simple docstring""" __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __a ( self : List[str] ): '''simple docstring''' __a = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) __a = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(SCREAMING_SNAKE_CASE__ ) __a = prepare_img() __a = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): __a = model(**SCREAMING_SNAKE_CASE__ ) __a = outputs.predicted_depth # verify the predicted depth __a = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE__ ) __a = torch.tensor( [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
582
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase_ ( snake_case__ , snake_case__ ): """simple docstring""" a_ :List[str] ="""nat""" a_ :int ={ """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : int=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=6_4 , SCREAMING_SNAKE_CASE__ : List[str]=[3, 4, 6, 5] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=[2, 4, 8, 1_6] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : int=3.0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Any=0.0_2 , SCREAMING_SNAKE_CASE__ : Tuple=1E-5 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) __a = patch_size __a = num_channels __a = embed_dim __a = depths __a = len(SCREAMING_SNAKE_CASE__ ) __a = num_heads __a = kernel_size __a = mlp_ratio __a = qkv_bias __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = drop_path_rate __a = hidden_act __a = layer_norm_eps __a = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __a = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE__ ) - 1) ) __a = layer_scale_init_value __a = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(SCREAMING_SNAKE_CASE__ ) + 1 )] __a , __a = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE__ , out_indices=SCREAMING_SNAKE_CASE__ , stage_names=self.stage_names )
582
1
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __A ( A_ ): '''simple docstring''' lowerCAmelCase : str = ["image_processor", "tokenizer"] lowerCAmelCase : Dict = "BlipImageProcessor" lowerCAmelCase : Tuple = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Dict ,_snake_case : int ,_snake_case : int ) -> str: """simple docstring""" lowercase__ : Union[str, Any] = False super().__init__(_snake_case ,_snake_case ) lowercase__ : Dict = self.image_processor def __call__( self : Dict ,_snake_case : ImageInput = None ,_snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,_snake_case : bool = True ,_snake_case : Union[bool, str, PaddingStrategy] = False ,_snake_case : Union[bool, str, TruncationStrategy] = None ,_snake_case : Optional[int] = None ,_snake_case : int = 0 ,_snake_case : Optional[int] = None ,_snake_case : Optional[bool] = None ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = False ,_snake_case : bool = True ,_snake_case : Optional[Union[str, TensorType]] = None ,**_snake_case : Dict ,) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: lowercase__ : str = self.tokenizer lowercase__ : List[str] = self.tokenizer( text=_snake_case ,add_special_tokens=_snake_case ,padding=_snake_case ,truncation=_snake_case ,max_length=_snake_case ,stride=_snake_case ,pad_to_multiple_of=_snake_case ,return_attention_mask=_snake_case ,return_overflowing_tokens=_snake_case ,return_special_tokens_mask=_snake_case ,return_offsets_mapping=_snake_case ,return_token_type_ids=_snake_case ,return_length=_snake_case ,verbose=_snake_case ,return_tensors=_snake_case ,**_snake_case ,) return text_encoding # add pixel_values lowercase__ : Dict = self.image_processor(_snake_case ,return_tensors=_snake_case ) if text is not None: lowercase__ : str = self.tokenizer( text=_snake_case ,add_special_tokens=_snake_case ,padding=_snake_case ,truncation=_snake_case ,max_length=_snake_case ,stride=_snake_case ,pad_to_multiple_of=_snake_case ,return_attention_mask=_snake_case ,return_overflowing_tokens=_snake_case ,return_special_tokens_mask=_snake_case ,return_offsets_mapping=_snake_case ,return_token_type_ids=_snake_case ,return_length=_snake_case ,verbose=_snake_case ,return_tensors=_snake_case ,**_snake_case ,) else: lowercase__ : Union[str, Any] = None if text_encoding is not None: encoding_image_processor.update(_snake_case ) return encoding_image_processor def UpperCAmelCase ( self : Union[str, Any] ,*_snake_case : Union[str, Any] ,**_snake_case : Union[str, Any] ) -> List[str]: """simple docstring""" return self.tokenizer.batch_decode(*_snake_case ,**_snake_case ) def UpperCAmelCase ( self : List[Any] ,*_snake_case : Optional[int] ,**_snake_case : Optional[Any] ) -> Any: """simple docstring""" return self.tokenizer.decode(*_snake_case ,**_snake_case ) @property def UpperCAmelCase ( self : Any ) -> int: """simple docstring""" lowercase__ : Tuple = self.tokenizer.model_input_names lowercase__ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
122
"""simple docstring""" 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 TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): '''simple docstring''' @slow def UpperCAmelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" lowercase__ : List[str] = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''' ) lowercase__ : Any = { '''input_ids''': tf.convert_to_tensor([[0, 2_646, 10_269, 83, 99_942, 2]] ,dtype=tf.intaa ), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] ,dtype=tf.intaa ), } lowercase__ : List[Any] = model(_snake_case )['''last_hidden_state'''] lowercase__ : Any = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape ,_snake_case ) # compare the actual values for a slice. lowercase__ : Optional[Any] = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] ,dtype=tf.floataa ,) self.assertTrue(np.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
122
1
"""simple docstring""" def lowercase__() ->List[str]: """simple docstring""" lowercase__ : Optional[int]= 0 for i in range(1 , 1_001 ): total += i**i return str(snake_case__ )[-10:] if __name__ == "__main__": print(solution())
218
"""simple docstring""" A_ = 2_56 # Modulus to hash a string A_ = 1_00_00_03 def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str ): """simple docstring""" _snake_case : Any = len(snake_case__ ) _snake_case : Tuple = len(snake_case__ ) if p_len > t_len: return False _snake_case : str = 0 _snake_case : Tuple = 0 _snake_case : Tuple = 1 # Calculating the hash of pattern and substring of text for i in range(snake_case__ ): _snake_case : Optional[int] = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus _snake_case : int = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue _snake_case : Any = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash _snake_case : List[str] = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = """abc1abc12""" _snake_case : Tuple = """alskfjaldsabc1abc1abc12k23adsfabcabc""" _snake_case : Optional[Any] = """alskfjaldsk23adsfabcabc""" assert rabin_karp(snake_case__ , snake_case__ ) and not rabin_karp(snake_case__ , snake_case__ ) # Test 2) _snake_case : Tuple = """ABABX""" _snake_case : Optional[Any] = """ABABZABABYABABX""" assert rabin_karp(snake_case__ , snake_case__ ) # Test 3) _snake_case : Union[str, Any] = """AAAB""" _snake_case : str = """ABAAAAAB""" assert rabin_karp(snake_case__ , snake_case__ ) # Test 4) _snake_case : List[str] = """abcdabcy""" _snake_case : Optional[int] = """abcxabcdabxabcdabcdabcy""" assert rabin_karp(snake_case__ , snake_case__ ) # Test 5) _snake_case : Union[str, Any] = """Lü""" _snake_case : Optional[int] = """Lüsai""" assert rabin_karp(snake_case__ , snake_case__ ) _snake_case : Any = """Lue""" assert not rabin_karp(snake_case__ , snake_case__ ) print("""Success.""" ) if __name__ == "__main__": test_rabin_karp()
609
0
__magic_name__ : Optional[Any] = 0 # The first color of the flag. __magic_name__ : Dict = 1 # The second color of the flag. __magic_name__ : Optional[int] = 2 # The third color of the flag. __magic_name__ : int = (red, white, blue) def lowerCAmelCase ( snake_case__ : list )-> list: if not sequence: return [] if len(snake_case__ ) == 1: return list(snake_case__ ) A_ = 0 A_ = len(snake_case__ ) - 1 A_ = 0 while mid <= high: if sequence[mid] == colors[0]: A_ , A_ = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: A_ , A_ = sequence[high], sequence[mid] high -= 1 else: A_ = f'The elements inside the sequence must contains only {colors} values' raise ValueError(snake_case__ ) return sequence if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ : str = input('Enter numbers separated by commas:\n').strip() __magic_name__ : List[str] = [int(item.strip()) for item in user_input.split(',')] print(f"""{dutch_national_flag_sort(unsorted)}""")
608
import math def lowerCAmelCase ( snake_case__ : float , snake_case__ : float )-> float: return math.pow(snake_case__ , 2 ) - a def lowerCAmelCase ( snake_case__ : float )-> float: return 2 * x def lowerCAmelCase ( snake_case__ : float )-> float: A_ = 2.0 while start <= a: A_ = math.pow(snake_case__ , 2 ) return start def lowerCAmelCase ( snake_case__ : float , snake_case__ : int = 9999 , snake_case__ : float = 0.0_0_0_0_0_0_0_0_0_0_0_0_0_1 )-> float: if a < 0: raise ValueError("math domain error" ) A_ = get_initial_point(snake_case__ ) for _ in range(snake_case__ ): A_ = value A_ = value - fx(snake_case__ , snake_case__ ) / fx_derivative(snake_case__ ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
608
1
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> Optional[Any]: assert isinstance(__snake_case , __snake_case ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Optional[Any]: _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _UpperCAmelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case , keep_in_memory=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Optional[int]: _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _UpperCAmelCase = features.copy() if features else default_expected_features _UpperCAmelCase = ( Features({feature: Value(__snake_case ) for feature, dtype in features.items()} ) if features is not None else None ) _UpperCAmelCase = ParquetDatasetReader(__snake_case , features=__snake_case , cache_dir=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Any: _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _UpperCAmelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case , split=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Any: if issubclass(__snake_case , __snake_case ): _UpperCAmelCase = parquet_path elif issubclass(__snake_case , __snake_case ): _UpperCAmelCase = [parquet_path] _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _UpperCAmelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case=("train",) ) -> List[str]: assert isinstance(__snake_case , __snake_case ) for split in splits: _UpperCAmelCase = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Tuple: _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _UpperCAmelCase = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=__snake_case , keep_in_memory=__snake_case ).read() _check_parquet_datasetdict(__snake_case , __snake_case ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> Optional[Any]: _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _UpperCAmelCase = features.copy() if features else default_expected_features _UpperCAmelCase = ( Features({feature: Value(__snake_case ) for feature, dtype in features.items()} ) if features is not None else None ) _UpperCAmelCase = ParquetDatasetReader({"""train""": parquet_path} , features=__snake_case , cache_dir=__snake_case ).read() _check_parquet_datasetdict(__snake_case , __snake_case ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> List[Any]: if split: _UpperCAmelCase = {split: parquet_path} else: _UpperCAmelCase = """train""" _UpperCAmelCase = {"""train""": parquet_path, """test""": parquet_path} _UpperCAmelCase = tmp_path / """cache""" _UpperCAmelCase = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _UpperCAmelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case ).read() _check_parquet_datasetdict(__snake_case , __snake_case , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> Dict: _UpperCAmelCase = ParquetDatasetWriter(__snake_case , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _UpperCAmelCase = pq.ParquetFile(tmp_path / """foo.parquet""" ) _UpperCAmelCase = pf.read() assert dataset.data.table == output_table def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> List[Any]: _UpperCAmelCase = str(shared_datadir / """test_image_rgb.jpg""" ) _UpperCAmelCase = {"""image""": [image_path]} _UpperCAmelCase = Features({"""image""": Image()} ) _UpperCAmelCase = Dataset.from_dict(__snake_case , features=__snake_case ) _UpperCAmelCase = ParquetDatasetWriter(__snake_case , tmp_path / """foo.parquet""" ) assert writer.write() > 0 _UpperCAmelCase = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features _UpperCAmelCase = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=__snake_case ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> List[Any]: assert get_writer_batch_size(__snake_case ) == expected
108
def _lowerCAmelCase ( _lowerCAmelCase ,_lowerCAmelCase ): '''simple docstring''' A_ : Any = [0 for i in range(r + 1 )] # nc0 = 1 A_ : List[Any] = 1 for i in range(1 ,n + 1 ): # to compute current row from previous row. A_ : Tuple = min(_lowerCAmelCase ,_lowerCAmelCase ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
569
0
import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : str = {"""vocab_file""": """vocab.txt""", """emoji_file""": """emoji.json"""} _lowerCamelCase : Union[str, Any] = { """vocab_file""": { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt""", }, """emoji_file""": { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json""", }, } _lowerCamelCase : Tuple = { """abeja/gpt-neox-japanese-2.7b""": 2048, } def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" with open(lowercase_ , '''r''' , encoding='''utf-8''' ) as f: A__ = json.loads(f.read() ) A__ = collections.OrderedDict() A__ = collections.OrderedDict() A__ = collections.OrderedDict() with open(lowercase_ , '''r''' , encoding='''utf-8''' ) as f: A__ = f.readlines() A__ = [[t.rstrip('''\n''' )] if (t == ''',''' or ''',''' not in t) else t.rstrip('''\n''' ).split(''',''' ) for t in token] for idx, b in enumerate(lowercase_ ): A__ = b A__ = idx for wd in b: A__ = idx return vocab, raw_vocab, ids_to_tokens, emoji class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any]="<|endoftext|>" , UpperCAmelCase__ : Optional[int]="<|endoftext|>" , UpperCAmelCase__ : Any="<|startoftext|>" , UpperCAmelCase__ : List[Any]="<|endoftext|>" , UpperCAmelCase__ : Dict=False , **UpperCAmelCase__ : Tuple , ) ->str: '''simple docstring''' super().__init__( unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , do_clean_text=UpperCAmelCase__ , **UpperCAmelCase__ , ) if not os.path.isfile(UpperCAmelCase__): raise ValueError( f"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained""" ''' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''') if not os.path.isfile(UpperCAmelCase__): raise ValueError( f"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google""" ''' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''') A__ = do_clean_text A__ , A__ , A__ , A__ = load_vocab_and_emoji(UpperCAmelCase__ , UpperCAmelCase__) A__ = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->str: '''simple docstring''' return len(self.raw_vocab) def SCREAMING_SNAKE_CASE ( self : List[str]) ->int: '''simple docstring''' return dict(self.raw_vocab , **self.added_tokens_encoder) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : str) ->Union[str, Any]: '''simple docstring''' return self.subword_tokenizer.tokenize(UpperCAmelCase__ , clean=self.do_clean_text) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Union[str, Any]) ->Optional[Any]: '''simple docstring''' return self.vocab.get(UpperCAmelCase__ , self.vocab.get(self.unk_token)) def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' return self.subword_tokenizer.convert_id_to_token(UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : Optional[Any]) ->str: '''simple docstring''' A__ = ''''''.join(UpperCAmelCase__).strip() return out_string def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : "Conversation") ->List[int]: '''simple docstring''' A__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__) + [self.eos_token_id]) if len(UpperCAmelCase__) > self.model_max_length: A__ = input_ids[-self.model_max_length :] return input_ids def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' A__ = 0 if os.path.isdir(UpperCAmelCase__): A__ = os.path.join( UpperCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) A__ = os.path.join( UpperCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''emoji_file''']) else: A__ = ( (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''vocab_file'''] ) A__ = ( (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''emoji_file'''] ) with open(UpperCAmelCase__ , '''w''' , encoding='''utf-8''') as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( f"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''') A__ = token_index writer.write(''','''.join(UpperCAmelCase__) + '''\n''') index += 1 with open(UpperCAmelCase__ , '''w''' , encoding='''utf-8''') as writer: json.dump(self.emoji , UpperCAmelCase__) return vocab_file, emoji_file class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any]) ->List[str]: '''simple docstring''' A__ = vocab # same as swe A__ = ids_to_tokens # same as bpe A__ = emoji A__ = np.max([len(UpperCAmelCase__) for w in self.vocab.keys()]) A__ = re.compile(R'''(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)''') A__ = re.compile(R'''[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*''') A__ = re.compile(R'''[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}''') A__ = re.compile( R'''([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''') A__ = re.compile( R'''(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''') A__ = re.compile( R'''((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*''') A__ = '''─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿''' A__ = '''▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟''' A__ = str.maketrans({k: '''<BLOCK>''' for k in keisen + blocks}) def __len__( self : Union[str, Any]) ->List[Any]: '''simple docstring''' return len(self.ids_to_tokens) def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : List[Any]) ->Dict: '''simple docstring''' A__ = self.content_repattera.sub('''<URL>''' , UpperCAmelCase__) A__ = self.content_repattera.sub('''<EMAIL>''' , UpperCAmelCase__) A__ = self.content_repattera.sub('''<TEL>''' , UpperCAmelCase__) A__ = self.content_repattera.sub('''<DATE>''' , UpperCAmelCase__) A__ = self.content_repattera.sub('''<DATE>''' , UpperCAmelCase__) A__ = self.content_repattera.sub('''<PRICE>''' , UpperCAmelCase__) A__ = content.translate(self.content_transa) while "<BLOCK><BLOCK>" in content: A__ = content.replace('''<BLOCK><BLOCK>''' , '''<BLOCK>''') return content def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str=False) ->List[Any]: '''simple docstring''' A__ = text.replace(''' ''' , '''<SP>''') A__ = text.replace(''' ''' , '''<SP>''') A__ = text.replace('''\r\n''' , '''<BR>''') A__ = text.replace('''\n''' , '''<BR>''') A__ = text.replace('''\r''' , '''<BR>''') A__ = text.replace('''\t''' , '''<TAB>''') A__ = text.replace('''—''' , '''ー''') A__ = text.replace('''−''' , '''ー''') for k, v in self.emoji["emoji"].items(): if k in text: A__ = text.replace(UpperCAmelCase__ , UpperCAmelCase__) if clean: A__ = self.clean_text(UpperCAmelCase__) def check_simbol(UpperCAmelCase__ : str): A__ = x.encode() if len(UpperCAmelCase__) == 1 and len(UpperCAmelCase__) == 2: A__ = (int(e[0]) << 8) + int(e[1]) if ( (c >= 0xc2_a1 and c <= 0xc2_bf) or (c >= 0xc7_80 and c <= 0xc7_83) or (c >= 0xca_b9 and c <= 0xcb_bf) or (c >= 0xcc_80 and c <= 0xcd_a2) ): return True return False def checkuae(UpperCAmelCase__ : Union[str, Any]): A__ = x.encode() if len(UpperCAmelCase__) == 1 and len(UpperCAmelCase__) == 3: A__ = (int(e[0]) << 16) + (int(e[1]) << 8) + int(e[2]) if c >= 0xe2_80_80 and c <= 0xe2_b0_7f: return True return False A__ = 0 A__ = [] while pos < len(UpperCAmelCase__): A__ = min(len(UpperCAmelCase__) , pos + self.maxlen + 1) if text[pos] == '''<''' else pos + 3 A__ = [] # (token_id, token, pos) for e in range(UpperCAmelCase__ , UpperCAmelCase__ , -1): A__ = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(UpperCAmelCase__) > 2: A__ = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e)) if len(UpperCAmelCase__) > 0: # the smallest token_id is adopted A__ , A__ , A__ = sorted(UpperCAmelCase__ , key=lambda UpperCAmelCase__: x[0])[0] result.append(UpperCAmelCase__) A__ = e else: A__ = pos + 1 A__ = text[pos:end] if check_simbol(UpperCAmelCase__): result.append('''<KIGOU>''') elif checkuae(UpperCAmelCase__): result.append('''<U2000U2BFF>''') else: for i in wd.encode('''utf-8'''): result.append('''<|byte%d|>''' % i) A__ = end return result def SCREAMING_SNAKE_CASE ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict="\n") ->Dict: '''simple docstring''' A__ = [] A__ = [] A__ = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2])) else: if len(UpperCAmelCase__) > 0: words.append(bytearray(UpperCAmelCase__).decode('''utf-8''' , errors='''replace''')) A__ = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji['''emoji_inv'''][word]) elif word == "<SP>": words.append(''' ''') elif word == "<BR>": words.append(UpperCAmelCase__) elif word == "<TAB>": words.append('''\t''') elif word == "<BLOCK>": words.append('''▀''') elif word == "<KIGOU>": words.append('''ǀ''') elif word == "<U2000U2BFF>": words.append('''‖''') else: words.append(UpperCAmelCase__) if len(UpperCAmelCase__) > 0: words.append(bytearray(UpperCAmelCase__).decode('''utf-8''' , errors='''replace''')) A__ = ''''''.join(UpperCAmelCase__) return text
177
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowerCamelCase : List[str] = (720, 1280) # Height, Width _lowerCamelCase : Optional[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowerCamelCase : List[Any] = 1 / 100 _lowerCamelCase : List[str] = """""" _lowerCamelCase : List[str] = """""" _lowerCamelCase : List[str] = """""" _lowerCamelCase : Union[str, Any] = 250 def SCREAMING_SNAKE_CASE ( ) -> None: """simple docstring""" A__ , A__ = get_dataset(lowercase_ , lowercase_ ) for index in range(lowercase_ ): A__ = random.sample(range(len(lowercase_ ) ) , 4 ) A__ , A__ , A__ = update_image_and_anno( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , filter_scale=lowercase_ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' A__ = random_chars(32 ) A__ = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] A__ = f"""{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}""" cva.imwrite(f"""{file_root}.jpg""" , lowercase_ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"""Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}""" ) A__ = [] for anno in new_annos: A__ = anno[3] - anno[1] A__ = anno[4] - anno[2] A__ = anno[1] + width / 2 A__ = anno[2] + height / 2 A__ = f"""{anno[0]} {x_center} {y_center} {width} {height}""" annos_list.append(lowercase_ ) with open(f"""{file_root}.txt""" , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> tuple[list, list]: """simple docstring""" A__ = [] A__ = [] for label_file in glob.glob(os.path.join(lowercase_ , '''*.txt''' ) ): A__ = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(lowercase_ ) as in_file: A__ = in_file.readlines() A__ = os.path.join(lowercase_ , f"""{label_name}.jpg""" ) A__ = [] for obj_list in obj_lists: A__ = obj_list.rstrip('''\n''' ).split(''' ''' ) A__ = float(obj[1] ) - float(obj[3] ) / 2 A__ = float(obj[2] ) - float(obj[4] ) / 2 A__ = float(obj[1] ) + float(obj[3] ) / 2 A__ = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(lowercase_ ) labels.append(lowercase_ ) return img_paths, labels def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" A__ = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) A__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) A__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) A__ = int(scale_x * output_size[1] ) A__ = int(scale_y * output_size[0] ) A__ = [] A__ = [] for i, index in enumerate(lowercase_ ): A__ = all_img_list[index] path_list.append(lowercase_ ) A__ = all_annos[index] A__ = cva.imread(lowercase_ ) if i == 0: # top-left A__ = cva.resize(lowercase_ , (divid_point_x, divid_point_y) ) A__ = img for bbox in img_annos: A__ = bbox[1] * scale_x A__ = bbox[2] * scale_y A__ = bbox[3] * scale_x A__ = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right A__ = cva.resize(lowercase_ , (output_size[1] - divid_point_x, divid_point_y) ) A__ = img for bbox in img_annos: A__ = scale_x + bbox[1] * (1 - scale_x) A__ = bbox[2] * scale_y A__ = scale_x + bbox[3] * (1 - scale_x) A__ = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left A__ = cva.resize(lowercase_ , (divid_point_x, output_size[0] - divid_point_y) ) A__ = img for bbox in img_annos: A__ = bbox[1] * scale_x A__ = scale_y + bbox[2] * (1 - scale_y) A__ = bbox[3] * scale_x A__ = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right A__ = cva.resize( lowercase_ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) A__ = img for bbox in img_annos: A__ = scale_x + bbox[1] * (1 - scale_x) A__ = scale_y + bbox[2] * (1 - scale_y) A__ = scale_x + bbox[3] * (1 - scale_x) A__ = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: A__ = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" A__ = ascii_lowercase + digits return "".join(random.choice(lowercase_ ) for _ in range(lowercase_ ) ) if __name__ == "__main__": main() print("""DONE ✅""")
177
1
'''simple docstring''' def _lowercase ( lowerCamelCase__ : str, lowerCamelCase__ : int ): return [sentence[i : i + ngram_size] for i in range(len(UpperCAmelCase__ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
131
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A = logging.get_logger(__name__) A = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __snake_case ( a__): _lowerCAmelCase = '''cvt''' def __init__( self, A=3, A=[7, 3, 3], A=[4, 2, 2], A=[2, 1, 1], A=[64, 192, 384], A=[1, 3, 6], A=[1, 2, 10], A=[4.0, 4.0, 4.0], A=[0.0, 0.0, 0.0], A=[0.0, 0.0, 0.0], A=[0.0, 0.0, 0.1], A=[True, True, True], A=[False, False, True], A=["dw_bn", "dw_bn", "dw_bn"], A=[3, 3, 3], A=[1, 1, 1], A=[2, 2, 2], A=[1, 1, 1], A=[1, 1, 1], A=0.02, A=1e-12, **A, ): """simple docstring""" super().__init__(**A ) lowerCamelCase : Tuple = num_channels lowerCamelCase : Optional[Any] = patch_sizes lowerCamelCase : str = patch_stride lowerCamelCase : Any = patch_padding lowerCamelCase : List[Any] = embed_dim lowerCamelCase : Dict = num_heads lowerCamelCase : List[Any] = depth lowerCamelCase : Tuple = mlp_ratio lowerCamelCase : List[Any] = attention_drop_rate lowerCamelCase : Union[str, Any] = drop_rate lowerCamelCase : Union[str, Any] = drop_path_rate lowerCamelCase : int = qkv_bias lowerCamelCase : List[Any] = cls_token lowerCamelCase : Optional[int] = qkv_projection_method lowerCamelCase : List[Any] = kernel_qkv lowerCamelCase : int = padding_kv lowerCamelCase : str = stride_kv lowerCamelCase : Any = padding_q lowerCamelCase : List[str] = stride_q lowerCamelCase : List[str] = initializer_range lowerCamelCase : Optional[Any] = layer_norm_eps
320
0
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( 'The RoBERTa Model transformer with early exiting (DeeRoBERTa). ' , UpperCAmelCase , ) class lowerCamelCase__ ( UpperCAmelCase ): """simple docstring""" _UpperCamelCase : str = RobertaConfig _UpperCamelCase : List[Any] = 'roberta' def __init__( self , snake_case ): '''simple docstring''' super().__init__(snake_case ) UpperCamelCase__ = RobertaEmbeddings(snake_case ) self.init_weights() @add_start_docstrings( 'RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. ' , UpperCAmelCase , ) class lowerCamelCase__ ( UpperCAmelCase ): """simple docstring""" _UpperCamelCase : Union[str, Any] = RobertaConfig _UpperCamelCase : str = 'roberta' def __init__( self , snake_case ): '''simple docstring''' super().__init__(snake_case ) UpperCamelCase__ = config.num_labels UpperCamelCase__ = config.num_hidden_layers UpperCamelCase__ = DeeRobertaModel(snake_case ) UpperCamelCase__ = nn.Dropout(config.hidden_dropout_prob ) UpperCamelCase__ = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(snake_case ) def snake_case__ ( self , snake_case=None , snake_case=None , snake_case=None , snake_case=None , snake_case=None , snake_case=None , snake_case=None , snake_case=-1 , snake_case=False , ): '''simple docstring''' UpperCamelCase__ = self.num_layers try: UpperCamelCase__ = self.roberta( snake_case , attention_mask=snake_case , token_type_ids=snake_case , position_ids=snake_case , head_mask=snake_case , inputs_embeds=snake_case , ) UpperCamelCase__ = outputs[1] UpperCamelCase__ = self.dropout(snake_case ) UpperCamelCase__ = self.classifier(snake_case ) UpperCamelCase__ = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: UpperCamelCase__ = e.message UpperCamelCase__ = e.exit_layer UpperCamelCase__ = outputs[0] if not self.training: UpperCamelCase__ = entropy(snake_case ) UpperCamelCase__ = [] UpperCamelCase__ = [] if labels is not None: if self.num_labels == 1: # We are doing regression UpperCamelCase__ = MSELoss() UpperCamelCase__ = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: UpperCamelCase__ = CrossEntropyLoss() UpperCamelCase__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits UpperCamelCase__ = [] for highway_exit in outputs[-1]: UpperCamelCase__ = highway_exit[0] if not self.training: highway_logits_all.append(snake_case ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression UpperCamelCase__ = MSELoss() UpperCamelCase__ = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: UpperCamelCase__ = CrossEntropyLoss() UpperCamelCase__ = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(snake_case ) if train_highway: UpperCamelCase__ = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: UpperCamelCase__ = (loss,) + outputs if not self.training: UpperCamelCase__ = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: UpperCamelCase__ = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
185
from typing import Any class lowerCamelCase__ : """simple docstring""" def __init__( self , snake_case ): '''simple docstring''' UpperCamelCase__ = data UpperCamelCase__ = None class lowerCamelCase__ : """simple docstring""" def __init__( self ): '''simple docstring''' UpperCamelCase__ = None def snake_case__ ( self ): '''simple docstring''' UpperCamelCase__ = self.head while temp is not None: print(temp.data , end=" " ) UpperCamelCase__ = temp.next print() def snake_case__ ( self , snake_case ): '''simple docstring''' UpperCamelCase__ = Node(snake_case ) UpperCamelCase__ = self.head UpperCamelCase__ = new_node def snake_case__ ( self , snake_case , snake_case ): '''simple docstring''' if node_data_a == node_data_a: return else: UpperCamelCase__ = self.head while node_a is not None and node_a.data != node_data_a: UpperCamelCase__ = node_a.next UpperCamelCase__ = self.head while node_a is not None and node_a.data != node_data_a: UpperCamelCase__ = node_a.next if node_a is None or node_a is None: return UpperCamelCase__, UpperCamelCase__ = node_a.data, node_a.data if __name__ == "__main__": __UpperCamelCase = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
185
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=__lowercase ) class _A ( __lowercase ): __a = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) __a = Features({"""audio""": Audio()} ) __a = Features({"""transcription""": Value("""string""" )} ) __a = "audio" __a = "transcription" def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): if self.audio_column not in features: raise ValueError(F"Column {self.audio_column} is not present in features." ) if not isinstance(features[self.audio_column] , _SCREAMING_SNAKE_CASE ): raise ValueError(F"Column {self.audio_column} is not an Audio type." ) _UpperCAmelCase = copy.deepcopy(self ) _UpperCAmelCase = self.input_schema.copy() _UpperCAmelCase = features[self.audio_column] _UpperCAmelCase = input_schema return task_template @property def UpperCAmelCase ( self ): return {self.audio_column: "audio", self.transcription_column: "transcription"}
518
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
518
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _lowerCAmelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = ["pixel_values"] def __init__( self : int , _A : bool = True , _A : Dict[str, int] = None , _A : int = 0.9 , _A : PILImageResampling = PILImageResampling.BICUBIC , _A : bool = True , _A : Dict[str, int] = None , _A : Union[int, float] = 1 / 255 , _A : bool = True , _A : bool = True , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , **_A : Any , ): super().__init__(**_A ) _UpperCamelCase = size if size is not None else {'''shortest_edge''': 224} _UpperCamelCase = get_size_dict(_A , default_to_square=_A ) _UpperCamelCase = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} _UpperCamelCase = get_size_dict(_A , param_name='''crop_size''' ) _UpperCamelCase = do_resize _UpperCamelCase = size _UpperCamelCase = crop_pct _UpperCamelCase = resample _UpperCamelCase = do_center_crop _UpperCamelCase = crop_size _UpperCamelCase = do_rescale _UpperCamelCase = rescale_factor _UpperCamelCase = do_normalize _UpperCamelCase = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _UpperCamelCase = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : int , _A : np.ndarray , _A : Dict[str, int] , _A : Optional[float] = None , _A : PILImageResampling = PILImageResampling.BICUBIC , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Union[str, Any] , ): _UpperCamelCase = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(F"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) if crop_pct is not None: if "shortest_edge" in size: _UpperCamelCase = int(size['''shortest_edge'''] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: _UpperCamelCase = int(size['''height'''] / crop_pct ) else: _UpperCamelCase = (int(size['''height'''] / crop_pct ), int(size['''width'''] / crop_pct )) else: raise ValueError('''Invalid size for resize: {}'''.format(_A ) ) _UpperCamelCase = get_resize_output_image_size(_A , size=_A , default_to_square=_A ) else: if "shortest_edge" in size: _UpperCamelCase = get_resize_output_image_size(_A , size=size['''shortest_edge'''] , default_to_square=_A ) elif "height" in size and "width" in size: _UpperCamelCase = (size['''height'''], size['''width''']) else: raise ValueError('''Invalid size for resize: {}'''.format(_A ) ) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def UpperCamelCase_ ( self : List[Any] , _A : np.ndarray , _A : Dict[str, int] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Union[str, Any] , ): _UpperCamelCase = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(F"""size must contain 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(_A , size=(size['''height'''], size['''width''']) , data_format=_A , **_A ) def UpperCamelCase_ ( self : Dict , _A : np.ndarray , _A : Union[int, float] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Tuple , ): return rescale(_A , scale=_A , data_format=_A , **_A ) def UpperCamelCase_ ( self : Any , _A : np.ndarray , _A : Union[float, List[float]] , _A : Union[float, List[float]] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Tuple , ): return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def UpperCamelCase_ ( self : List[Any] , _A : ImageInput , _A : bool = None , _A : Dict[str, int] = None , _A : int = None , _A : PILImageResampling = None , _A : bool = None , _A : Dict[str, int] = None , _A : bool = None , _A : float = None , _A : bool = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[str, TensorType]] = None , _A : ChannelDimension = ChannelDimension.FIRST , **_A : Dict , ): _UpperCamelCase = do_resize if do_resize is not None else self.do_resize _UpperCamelCase = crop_pct if crop_pct is not None else self.crop_pct _UpperCamelCase = resample if resample is not None else self.resample _UpperCamelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale _UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize _UpperCamelCase = image_mean if image_mean is not None else self.image_mean _UpperCamelCase = image_std if image_std is not None else self.image_std _UpperCamelCase = size if size is not None else self.size _UpperCamelCase = get_size_dict(_A , default_to_square=_A ) _UpperCamelCase = crop_size if crop_size is not None else self.crop_size _UpperCamelCase = get_size_dict(_A , param_name='''crop_size''' ) _UpperCamelCase = make_list_of_images(_A ) if not valid_images(_A ): 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 or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_pct is None: raise ValueError('''Crop_pct must be specified if do_center_crop 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('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _UpperCamelCase = [to_numpy_array(_A ) for image in images] if do_resize: _UpperCamelCase = [self.resize(image=_A , size=_A , crop_pct=_A , resample=_A ) for image in images] if do_center_crop: _UpperCamelCase = [self.center_crop(image=_A , size=_A ) for image in images] if do_rescale: _UpperCamelCase = [self.rescale(image=_A , scale=_A ) for image in images] if do_normalize: _UpperCamelCase = [self.normalize(image=_A , mean=_A , std=_A ) for image in images] _UpperCamelCase = [to_channel_dimension_format(_A , _A ) for image in images] _UpperCamelCase = {'''pixel_values''': images} return BatchFeature(data=_A , tensor_type=_A )
714
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): # Return True if there is node that has not iterated. _UpperCamelCase = [False] * len(__snake_case ) _UpperCamelCase = [] queue.append(__snake_case ) _UpperCamelCase = True while queue: _UpperCamelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__snake_case ) _UpperCamelCase = True _UpperCamelCase = u return visited[t] def _snake_case ( __snake_case , __snake_case , __snake_case ): # This array is filled by BFS and to store path _UpperCamelCase = [-1] * (len(__snake_case )) _UpperCamelCase = 0 while bfs(__snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = float('''Inf''' ) _UpperCamelCase = sink while s != source: # Find the minimum value in select path _UpperCamelCase = min(__snake_case , graph[parent[s]][s] ) _UpperCamelCase = parent[s] max_flow += path_flow _UpperCamelCase = sink while v != source: _UpperCamelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _UpperCamelCase = parent[v] return max_flow _lowerCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _lowerCAmelCase, _lowerCAmelCase = 0, 5 print(ford_fulkerson(graph, source, sink))
71
0
from ...configuration_utils import PretrainedConfig a_ = { 'google/tapas-base-finetuned-sqa': ( 'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json' ), 'google/tapas-base-finetuned-wtq': ( 'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json' ), 'google/tapas-base-finetuned-wikisql-supervised': ( 'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json' ), 'google/tapas-base-finetuned-tabfact': ( 'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json' ), } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='tapas' def __init__( self : int , a : Optional[Any]=3_0522 , a : Optional[Any]=768 , a : Dict=12 , a : str=12 , a : str=3072 , a : Optional[int]="gelu" , a : Optional[Any]=0.1 , a : Any=0.1 , a : List[str]=1024 , a : str=[3, 256, 256, 2, 256, 256, 10] , a : Tuple=0.02 , a : List[Any]=1e-12 , a : Tuple=0 , a : int=10.0 , a : Optional[Any]=0 , a : Optional[int]=1.0 , a : Optional[int]=None , a : List[Any]=1.0 , a : Optional[int]=False , a : int=None , a : Optional[int]=1.0 , a : List[Any]=1.0 , a : List[str]=False , a : int=False , a : Any="ratio" , a : Tuple=None , a : Optional[int]=None , a : List[str]=64 , a : str=32 , a : Union[str, Any]=False , a : Optional[Any]=True , a : Union[str, Any]=False , a : List[Any]=False , a : Optional[int]=True , a : int=False , a : List[Any]=None , a : Optional[int]=None , **a : int , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=a , **a ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) SCREAMING_SNAKE_CASE : Tuple = vocab_size SCREAMING_SNAKE_CASE : Any = hidden_size SCREAMING_SNAKE_CASE : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : Any = type_vocab_sizes SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Any = layer_norm_eps # Fine-tuning task hyperparameters SCREAMING_SNAKE_CASE : Union[str, Any] = positive_label_weight SCREAMING_SNAKE_CASE : Union[str, Any] = num_aggregation_labels SCREAMING_SNAKE_CASE : int = aggregation_loss_weight SCREAMING_SNAKE_CASE : List[Any] = use_answer_as_supervision SCREAMING_SNAKE_CASE : List[str] = answer_loss_importance SCREAMING_SNAKE_CASE : Optional[int] = use_normalized_answer_loss SCREAMING_SNAKE_CASE : Dict = huber_loss_delta SCREAMING_SNAKE_CASE : List[str] = temperature SCREAMING_SNAKE_CASE : int = aggregation_temperature SCREAMING_SNAKE_CASE : Optional[int] = use_gumbel_for_cells SCREAMING_SNAKE_CASE : Optional[int] = use_gumbel_for_aggregation SCREAMING_SNAKE_CASE : Tuple = average_approximation_function SCREAMING_SNAKE_CASE : Optional[int] = cell_selection_preference SCREAMING_SNAKE_CASE : Optional[Any] = answer_loss_cutoff SCREAMING_SNAKE_CASE : int = max_num_rows SCREAMING_SNAKE_CASE : Tuple = max_num_columns SCREAMING_SNAKE_CASE : Optional[Any] = average_logits_per_cell SCREAMING_SNAKE_CASE : str = select_one_column SCREAMING_SNAKE_CASE : Any = allow_empty_column_selection SCREAMING_SNAKE_CASE : Tuple = init_cell_selection_weights_to_zero SCREAMING_SNAKE_CASE : Tuple = reset_position_index_per_cell SCREAMING_SNAKE_CASE : Union[str, Any] = disable_per_token_loss # Aggregation hyperparameters SCREAMING_SNAKE_CASE : str = aggregation_labels SCREAMING_SNAKE_CASE : Any = no_aggregation_label_index if isinstance(self.aggregation_labels , a ): SCREAMING_SNAKE_CASE : str = {int(a ): v for k, v in aggregation_labels.items()}
25
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_mctct": ["MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MCTCTConfig"], "feature_extraction_mctct": ["MCTCTFeatureExtractor"], "processing_mctct": ["MCTCTProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST", "MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
695
0
import math class lowerCAmelCase_ : def a_ ( self : Tuple , UpperCAmelCase_ : list[list[float]] , UpperCAmelCase_ : list[int] ) -> int: '''simple docstring''' _UpperCAmelCase : Optional[int] = 0.0 _UpperCAmelCase : Any = 0.0 for i in range(len(UpperCAmelCase_ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def a_ ( self : int , UpperCAmelCase_ : list[list[int | float]] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : float ) -> list[list[int | float]]: '''simple docstring''' for i in range(len(UpperCAmelCase_ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def _A ( ): # Training Examples ( m, n ) _UpperCAmelCase : Tuple = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) _UpperCAmelCase : str = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training _UpperCAmelCase : Optional[Any] = SelfOrganizingMap() _UpperCAmelCase : Dict = 3 _UpperCAmelCase : int = 0.5 for _ in range(_UpperCamelCase ): for j in range(len(_UpperCamelCase ) ): # training sample _UpperCAmelCase : List[str] = training_samples[j] # Compute the winning vector _UpperCAmelCase : str = self_organizing_map.get_winner(_UpperCamelCase , _UpperCamelCase ) # Update the winning vector _UpperCAmelCase : Optional[int] = self_organizing_map.update(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # classify test sample _UpperCAmelCase : Optional[Any] = [0, 0, 0, 1] _UpperCAmelCase : List[str] = self_organizing_map.get_winner(_UpperCamelCase , _UpperCamelCase ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
416
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class lowerCAmelCase_ ( lowercase_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Optional[Any] = PriorTransformer SCREAMING_SNAKE_CASE_ : List[Any] = """hidden_states""" @property def a_ ( self : str ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase : Optional[Any] = 4 _UpperCAmelCase : int = 8 _UpperCAmelCase : Any = 7 _UpperCAmelCase : Optional[int] = floats_tensor((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) _UpperCAmelCase : str = floats_tensor((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) _UpperCAmelCase : List[str] = floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(UpperCAmelCase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def a_ ( self : Any , UpperCAmelCase_ : List[Any]=0 ) -> Dict: '''simple docstring''' torch.manual_seed(UpperCAmelCase_ ) _UpperCAmelCase : Any = 4 _UpperCAmelCase : int = 8 _UpperCAmelCase : Optional[Any] = 7 _UpperCAmelCase : Union[str, Any] = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) _UpperCAmelCase : List[str] = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) _UpperCAmelCase : Dict = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(UpperCAmelCase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def a_ ( self : int ) -> str: '''simple docstring''' return (4, 8) @property def a_ ( self : Any ) -> int: '''simple docstring''' return (4, 8) def a_ ( self : int ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : List[str] = { '''num_attention_heads''': 2, '''attention_head_dim''': 4, '''num_layers''': 2, '''embedding_dim''': 8, '''num_embeddings''': 7, '''additional_embeddings''': 4, } _UpperCAmelCase : List[str] = self.dummy_input return init_dict, inputs_dict def a_ ( self : Any ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase : Any = PriorTransformer.from_pretrained( '''hf-internal-testing/prior-dummy''' , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(UpperCAmelCase_ ) _UpperCAmelCase : Any = model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def a_ ( self : List[Any] ) -> Dict: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase : List[str] = self.prepare_init_args_and_inputs_for_common() _UpperCAmelCase : str = self.model_class(**UpperCAmelCase_ ) _UpperCAmelCase : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase : Optional[int] = [*signature.parameters.keys()] _UpperCAmelCase : List[str] = ['''hidden_states''', '''timestep'''] self.assertListEqual(arg_names[:2] , UpperCAmelCase_ ) def a_ ( self : Dict ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : List[str] = PriorTransformer.from_pretrained('''hf-internal-testing/prior-dummy''' ) _UpperCAmelCase : Optional[int] = model.to(UpperCAmelCase_ ) if hasattr(UpperCAmelCase_ , '''set_default_attn_processor''' ): model.set_default_attn_processor() _UpperCAmelCase : Tuple = self.get_dummy_seed_input() with torch.no_grad(): _UpperCAmelCase : List[str] = model(**UpperCAmelCase_ )[0] _UpperCAmelCase : List[str] = output[0, :5].flatten().cpu() print(UpperCAmelCase_ ) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. _UpperCAmelCase : List[str] = torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239] ) self.assertTrue(torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , rtol=1E-2 ) ) @slow class lowerCAmelCase_ ( unittest.TestCase ): def a_ ( self : List[Any] , UpperCAmelCase_ : Dict=1 , UpperCAmelCase_ : str=768 , UpperCAmelCase_ : List[Any]=77 , UpperCAmelCase_ : List[str]=0 ) -> List[Any]: '''simple docstring''' torch.manual_seed(UpperCAmelCase_ ) _UpperCAmelCase : Dict = batch_size _UpperCAmelCase : str = embedding_dim _UpperCAmelCase : Union[str, Any] = num_embeddings _UpperCAmelCase : int = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) _UpperCAmelCase : List[Any] = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) _UpperCAmelCase : Union[str, Any] = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(UpperCAmelCase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def a_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.5_861, 0.1_283, -0.0_931, 0.0_882, 0.4_476, 0.1_329, -0.0_498, 0.0_640]], [37, [-0.4_913, 0.0_110, -0.0_483, 0.0_541, 0.4_954, -0.0_170, 0.0_354, 0.1_651]], # fmt: on ] ) def a_ ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] ) -> Any: '''simple docstring''' _UpperCAmelCase : List[Any] = PriorTransformer.from_pretrained('''kandinsky-community/kandinsky-2-1-prior''' , subfolder='''prior''' ) model.to(UpperCAmelCase_ ) _UpperCAmelCase : Optional[int] = self.get_dummy_seed_input(seed=UpperCAmelCase_ ) with torch.no_grad(): _UpperCAmelCase : Dict = model(**UpperCAmelCase_ )[0] assert list(sample.shape ) == [1, 768] _UpperCAmelCase : int = sample[0, :8].flatten().cpu() print(UpperCAmelCase_ ) _UpperCAmelCase : Optional[int] = torch.tensor(UpperCAmelCase_ ) assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 )
416
1
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def __lowerCAmelCase ( A = "isbn/0140328726" ): UpperCAmelCase_ = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: UpperCAmelCase_ = F"{olid} is not a valid Open Library olid" raise ValueError(_SCREAMING_SNAKE_CASE ) return requests.get(F"https://openlibrary.org/{new_olid}.json" ).json() def __lowerCAmelCase ( A ): UpperCAmelCase_ = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } UpperCAmelCase_ = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} UpperCAmelCase_ = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] UpperCAmelCase_ = data["First sentence"]["value"] for key, value in data.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCAmelCase_ = ", ".join(_SCREAMING_SNAKE_CASE ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _a: Optional[Any] = input("""\nEnter the ISBN code to search (or 'quit' to stop): """).strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F'Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.') continue print(F'\nSearching Open Library for ISBN: {isbn}...\n') try: _a: Union[str, Any] = summarize_book(get_openlibrary_data(F'isbn/{isbn}')) print("""\n""".join(F'{key}: {value}' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F'Sorry, there are no results for ISBN: {isbn}.')
162
def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Any: lowercase__ = [0] * len(_SCREAMING_SNAKE_CASE ) lowercase__ = [] lowercase__ = [1] * len(_SCREAMING_SNAKE_CASE ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_SCREAMING_SNAKE_CASE ) ): if indegree[i] == 0: queue.append(_SCREAMING_SNAKE_CASE ) while queue: lowercase__ = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: lowercase__ = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_SCREAMING_SNAKE_CASE ) print(max(_SCREAMING_SNAKE_CASE ) ) # Adjacency list of Graph lowercase_ = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
235
0
def UpperCamelCase_( __magic_name__ : int ): """simple docstring""" _lowerCAmelCase :Any = int(__magic_name__ ) if decimal in (0, 1): # Exit cases for the recursion return str(__magic_name__ ) _lowerCAmelCase :Tuple = divmod(__magic_name__ , 2 ) return binary_recursive(__magic_name__ ) + str(__magic_name__ ) def UpperCamelCase_( __magic_name__ : str ): """simple docstring""" _lowerCAmelCase :int = str(__magic_name__ ).strip() if not number: raise ValueError('No input value was provided' ) _lowerCAmelCase :Optional[int] = '-' if number.startswith('-' ) else '' _lowerCAmelCase :List[Any] = number.lstrip('-' ) if not number.isnumeric(): raise ValueError('Input value is not an integer' ) return f"""{negative}0b{binary_recursive(int(__magic_name__ ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
714
import math import sys def UpperCamelCase_( __magic_name__ : int ): """simple docstring""" if number != int(__magic_name__ ): 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 _lowerCAmelCase :Optional[Any] = [-1] * (number + 1) _lowerCAmelCase :Optional[Any] = 0 for i in range(1 , number + 1 ): _lowerCAmelCase :Tuple = sys.maxsize _lowerCAmelCase :int = int(math.sqrt(__magic_name__ ) ) for j in range(1 , root + 1 ): _lowerCAmelCase :str = 1 + answers[i - (j**2)] _lowerCAmelCase :List[str] = min(__magic_name__ , __magic_name__ ) _lowerCAmelCase :Union[str, Any] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
382
0