code stringlengths 81 54k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from transformers.activations import gelu_new, gelu_python, get_activation
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Dict ) -> Optional[int]:
_A = torch.tensor([-1_00, -1, -0.1, 0, 0.1, 1.0, 1_00] )
_A = get_activation('''gelu''' )
self.assertTrue(torch.allclose(gelu_python(_A ) , torch_builtin(_A ) ) )
self.assertFalse(torch.allclose(gelu_python(_A ) , gelu_new(_A ) ) )
def __A ( self: Optional[int] ) -> List[str]:
_A = torch.tensor([-1_00, -1, -0.1, 0, 0.1, 1.0, 1_00] )
_A = get_activation('''gelu''' )
_A = get_activation('''gelu_10''' )
_A = torch_builtin(_A )
_A = geluaa(_A )
_A = torch.where(y_gelu_aa < 10.0 , 1 , 0 )
self.assertTrue(torch.max(_A ).item() == 10.0 )
self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) )
def __A ( self: Dict ) -> str:
get_activation('''gelu''' )
get_activation('''gelu_10''' )
get_activation('''gelu_fast''' )
get_activation('''gelu_new''' )
get_activation('''gelu_python''' )
get_activation('''gelu_pytorch_tanh''' )
get_activation('''linear''' )
get_activation('''mish''' )
get_activation('''quick_gelu''' )
get_activation('''relu''' )
get_activation('''sigmoid''' )
get_activation('''silu''' )
get_activation('''swish''' )
get_activation('''tanh''' )
with self.assertRaises(_A ):
get_activation('''bogus''' )
with self.assertRaises(_A ):
get_activation(_A )
def __A ( self: List[str] ) -> Tuple:
_A = get_activation('''gelu''' )
_A = 1
_A = get_activation('''gelu''' )
self.assertEqual(acta.a , 1 )
with self.assertRaises(_A ):
_A = acta.a
| 713 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = word.split()
def justify(_lowercase , _lowercase , _lowercase ) -> str:
_A = max_width - width
_A = len(_lowercase )
if len(_lowercase ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_A = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_A = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_A = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_lowercase ):
num_spaces_between_words_list[i] += 1
_A = []
for i in range(_lowercase ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * ''' ''' )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_lowercase )
_A = []
_A = []
_A = 0
for word in words:
if width + len(_lowercase ) + len(_lowercase ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_lowercase )
width += len(_lowercase )
else:
# justify the line and add it to result
answer.append(justify(_lowercase , _lowercase , _lowercase ) )
# reset new line and new width
_A ,_A = [word], len(_lowercase )
_A = max_width - width - len(_lowercase )
answer.append(''' '''.join(_lowercase ) + (remaining_spaces + 1) * ''' ''' )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 62 | 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
__A = 'src/diffusers'
__A = '.'
# This is to make sure the diffusers module imported is the one in the repo.
__A = importlib.util.spec_from_file_location(
'diffusers',
os.path.join(DIFFUSERS_PATH, '__init__.py'),
submodule_search_locations=[DIFFUSERS_PATH],
)
__A = spec.loader.load_module()
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R'''^\s*\)(\s*->.*:|:)\s*$''' , UpperCAmelCase__ ) is not None
def __A ( _lowercase ):
'''simple docstring'''
_A = object_name.split('''.''' )
_A = 0
# First let's find the module where our object lives.
_A = 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 = 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 = f.readlines()
# Now let's find the class / func in the code!
_A = ''''''
_A = 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 = 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 = lines[start_index:line_index]
return "".join(UpperCAmelCase__ )
__A = re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)')
__A = re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)')
__A = re.compile(R'<FILL\s+[^>]*>')
def __A ( _lowercase ):
'''simple docstring'''
_A = code.split('''\n''' )
_A = 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 __A ( _lowercase ):
'''simple docstring'''
_A = len(get_indent(UpperCAmelCase__ ) ) > 0
if has_indent:
_A = f"""class Bla:\n{code}"""
_A = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 , preview=UpperCAmelCase__ )
_A = black.format_str(UpperCAmelCase__ , mode=UpperCAmelCase__ )
_A ,_A = style_docstrings_in_code(UpperCAmelCase__ )
return result[len('''class Bla:\n''' ) :] if has_indent else result
def __A ( _lowercase , _lowercase=False ):
'''simple docstring'''
with open(UpperCAmelCase__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
_A = f.readlines()
_A = []
_A = 0
# Not a for loop cause `lines` is going to change (if `overwrite=True`).
while line_index < len(UpperCAmelCase__ ):
_A = _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 = search.groups()
_A = find_code_in_diffusers(UpperCAmelCase__ )
_A = get_indent(UpperCAmelCase__ )
_A = line_index + 1 if indent == theoretical_indent else line_index + 2
_A = theoretical_indent
_A = start_index
# Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment.
_A = True
while line_index < len(UpperCAmelCase__ ) and should_continue:
line_index += 1
if line_index >= len(UpperCAmelCase__ ):
break
_A = lines[line_index]
_A = _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 = lines[start_index:line_index]
_A = ''''''.join(UpperCAmelCase__ )
# Remove any nested `Copied from` comments to avoid circular copies
_A = [line for line in theoretical_code.split('''\n''' ) if _re_copy_warning.search(UpperCAmelCase__ ) is None]
_A = '''\n'''.join(UpperCAmelCase__ )
# Before comparing, use the `replace_pattern` on the original code.
if len(UpperCAmelCase__ ) > 0:
_A = replace_pattern.replace('''with''' , '''''' ).split(''',''' )
_A = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns]
for pattern in patterns:
if pattern is None:
continue
_A ,_A ,_A = pattern.groups()
_A = re.sub(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
if option.strip() == "all-casing":
_A = re.sub(obja.lower() , obja.lower() , UpperCAmelCase__ )
_A = 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 = blackify(lines[start_index - 1] + theoretical_code )
_A = 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 = lines[:start_index] + [theoretical_code] + lines[line_index:]
_A = 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 __A ( _lowercase = False ):
'''simple docstring'''
_A = glob.glob(os.path.join(UpperCAmelCase__ , '''**/*.py''' ) , recursive=UpperCAmelCase__ )
_A = []
for filename in all_files:
_A = 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 = '''\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__":
__A = argparse.ArgumentParser()
parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
__A = parser.parse_args()
check_copies(args.fix_and_overwrite)
| 714 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(_lowercase , '''utf-8''' )
with zstd.open(_lowercase , '''wb''' ) as f:
f.write(_lowercase )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , _lowercase ) , '''w''' ) as f:
f.write(_lowercase )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=_lowercase , extract_compressed_file=_lowercase )
_A = cached_path(_lowercase , download_config=_lowercase )
with open(_lowercase ) as f:
_A = f.read()
with open(_lowercase ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , _lowercase )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(_lowercase ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=_lowercase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowercase )
)
_A = cached_path(_lowercase , download_config=_lowercase )
assert Path(_lowercase ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(_lowercase ).resolve() )
assert cached_path(_lowercase ) == text_file
# relative path
_A = str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowercase ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(_lowercase ):
cached_path(_lowercase )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(_lowercase ):
cached_path(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(_lowercase ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( ):
'''simple docstring'''
with pytest.raises(_lowercase ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
http_get('''https://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
ftp_get('''ftp://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
fsspec_get('''s3://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
fsspec_head('''s3://huggingface.co''' )
| 62 | 0 |
'''simple docstring'''
from sympy import diff, lambdify, symbols
from sympy.functions import * # noqa: F403
def __A ( _lowercase , _lowercase , _lowercase = "x" , _lowercase = 10**-10 , _lowercase = 1 , ):
'''simple docstring'''
_A = symbols(_UpperCamelCase )
_A = lambdify(_UpperCamelCase , _UpperCamelCase )
_A = lambdify(_UpperCamelCase , diff(_UpperCamelCase , _UpperCamelCase ) )
_A = starting_point
while True:
if diff_function(_UpperCamelCase ) != 0:
_A = prev_guess - multiplicity * func(_UpperCamelCase ) / diff_function(
_UpperCamelCase )
else:
raise ZeroDivisionError('''Could not find root''' ) from None
# Precision is checked by comparing the difference of consecutive guesses
if abs(next_guess - prev_guess ) < precision:
return next_guess
_A = next_guess
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
# Find fourth Root of 5
print(f'The root of x**4 - 5 = 0 is {newton_raphson("x**4 -5", 0.4 +5j)}')
# Find value of e
print(
'The root of log(y) - 1 = 0 is ',
f'{newton_raphson("log(y) - 1", 2, variable="y")}',
)
# Exponential Roots
print(
'The root of exp(x) - 1 = 0 is',
f'{newton_raphson("exp(x) - 1", 10, precision=0.005)}',
)
# Find root of cos(x)
print(f'The root of cos(x) = 0 is {newton_raphson("cos(x)", 0)}')
| 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 |
import warnings
from ...utils import logging
from .image_processing_chinese_clip import ChineseCLIPImageProcessor
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE ( __UpperCAmelCase ):
"""simple docstring"""
def __init__( self: Tuple , *__A: Optional[Any] , **__A: int ) -> Any:
warnings.warn(
'''The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
''' Please use ChineseCLIPImageProcessor instead.''' , __A , )
super().__init__(*__A , **__A )
| 716 |
import flax.linen as nn
import jax
import jax.numpy as jnp
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: Tuple ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Dict , __A: Dict ) -> Tuple:
_A ,_A ,_A ,_A = hidden_states.shape
_A = jax.image.resize(
__A , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , )
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: List[str] ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Union[str, Any] , __A: List[Any] ) -> Union[str, Any]:
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = None
A_ = 0.0
A_ = None
A_ = jnp.floataa
def __A ( self: Dict ) -> Dict:
_A = self.in_channels if self.out_channels is None else self.out_channels
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = nn.Dense(__A , dtype=self.dtype )
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Dropout(self.dropout_prob )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
_A = None
if use_nin_shortcut:
_A = nn.Conv(
__A , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , )
def __call__( self: Dict , __A: List[Any] , __A: List[Any] , __A: Any=True ) -> List[Any]:
_A = hidden_states
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.conva(__A )
_A = self.time_emb_proj(nn.swish(__A ) )
_A = jnp.expand_dims(jnp.expand_dims(__A , 1 ) , 1 )
_A = hidden_states + temb
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.dropout(__A , __A )
_A = self.conva(__A )
if self.conv_shortcut is not None:
_A = self.conv_shortcut(__A )
return hidden_states + residual
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import _LazyModule
__A = {"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]}
if TYPE_CHECKING:
from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 717 |
def __A ( _lowercase ):
'''simple docstring'''
_A = [0] * len(_lowercase )
_A = []
_A = []
_A = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(_lowercase ) ):
if indegree[i] == 0:
queue.append(_lowercase )
while queue:
_A = queue.pop(0 )
cnt += 1
topo.append(_lowercase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(_lowercase )
if cnt != len(_lowercase ):
print('''Cycle exists''' )
else:
print(_lowercase )
# Adjacency List of Graph
__A = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 62 | 0 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(snake_case_ , '''utf-8''' )
with zstd.open(snake_case_ , '''wb''' ) as f:
f.write(snake_case_ )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , snake_case_ ) , '''w''' ) as f:
f.write(snake_case_ )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=snake_case_ , extract_compressed_file=snake_case_ )
_A = cached_path(snake_case_ , download_config=snake_case_ )
with open(snake_case_ ) as f:
_A = f.read()
with open(snake_case_ ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , snake_case_ )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(snake_case_ ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=snake_case_ )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=snake_case_ )
)
_A = cached_path(snake_case_ , download_config=snake_case_ )
assert Path(snake_case_ ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(snake_case_ ).resolve() )
assert cached_path(snake_case_ ) == text_file
# relative path
_A = str(Path(snake_case_ ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(snake_case_ ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(snake_case_ ):
cached_path(snake_case_ )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(snake_case_ ):
cached_path(snake_case_ )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(snake_case_ ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case_ )
def __A ( ):
'''simple docstring'''
with pytest.raises(snake_case_ ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case_ )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(snake_case_ ):
http_get('''https://huggingface.co''' , temp_file=snake_case_ )
with pytest.raises(snake_case_ ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case_ )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(snake_case_ ):
ftp_get('''ftp://huggingface.co''' , temp_file=snake_case_ )
with pytest.raises(snake_case_ ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , snake_case_ )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(snake_case_ ):
fsspec_get('''s3://huggingface.co''' , temp_file=snake_case_ )
with pytest.raises(snake_case_ ):
fsspec_head('''s3://huggingface.co''' )
| 718 |
import math
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 SchedulerMixin, SchedulerOutput
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = 1
@register_to_config
def __init__( self: Any , __A: int = 10_00 , __A: Optional[Union[np.ndarray, List[float]]] = None ) -> List[str]:
# set `betas`, `alphas`, `timesteps`
self.set_timesteps(__A )
# standard deviation of the initial noise distribution
_A = 1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
_A = 4
# running values
_A = []
def __A ( self: str , __A: int , __A: Union[str, torch.device] = None ) -> int:
_A = num_inference_steps
_A = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
_A = torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
_A = torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
_A = torch.sin(steps * math.pi / 2 ) ** 2
_A = (1.0 - self.betas**2) ** 0.5
_A = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
_A = timesteps.to(__A )
_A = []
def __A ( self: Tuple , __A: torch.FloatTensor , __A: int , __A: torch.FloatTensor , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
_A = (self.timesteps == timestep).nonzero().item()
_A = timestep_index + 1
_A = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(__A )
if len(self.ets ) == 1:
_A = self.ets[-1]
elif len(self.ets ) == 2:
_A = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
_A = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
_A = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
_A = self._get_prev_sample(__A , __A , __A , __A )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Optional[int] , __A: torch.FloatTensor , *__A: Tuple , **__A: List[Any] ) -> torch.FloatTensor:
return sample
def __A ( self: List[str] , __A: Optional[Any] , __A: Optional[Any] , __A: Any , __A: List[Any] ) -> List[Any]:
_A = self.alphas[timestep_index]
_A = self.betas[timestep_index]
_A = self.alphas[prev_timestep_index]
_A = self.betas[prev_timestep_index]
_A = (sample - sigma * ets) / max(__A , 1e-8 )
_A = next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self: List[str] ) -> Dict:
return self.config.num_train_timesteps
| 62 | 0 |
import flax.linen as nn
import jax.numpy as jnp
from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = 42
A_ = 0.0
A_ = 1
A_ = 1
A_ = True
A_ = False
A_ = False
A_ = False
A_ = jnp.floataa
def __A ( self: str ) -> str:
_A = []
_A = []
for i in range(self.num_layers ):
_A = self.in_channels if i == 0 else self.out_channels
_A = FlaxResnetBlockaD(
in_channels=__A , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__A )
_A = FlaxTransformeraDModel(
in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , )
attentions.append(__A )
_A = resnets
_A = attentions
if self.add_downsample:
_A = FlaxDownsampleaD(self.out_channels , dtype=self.dtype )
def __call__( self: int , __A: int , __A: Any , __A: Tuple , __A: int=True ) -> Any:
_A = ()
for resnet, attn in zip(self.resnets , self.attentions ):
_A = resnet(__A , __A , deterministic=__A )
_A = attn(__A , __A , deterministic=__A )
output_states += (hidden_states,)
if self.add_downsample:
_A = self.downsamplers_a(__A )
output_states += (hidden_states,)
return hidden_states, output_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = 42
A_ = 0.0
A_ = 1
A_ = True
A_ = jnp.floataa
def __A ( self: List[Any] ) -> Optional[Any]:
_A = []
for i in range(self.num_layers ):
_A = self.in_channels if i == 0 else self.out_channels
_A = FlaxResnetBlockaD(
in_channels=__A , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__A )
_A = resnets
if self.add_downsample:
_A = FlaxDownsampleaD(self.out_channels , dtype=self.dtype )
def __call__( self: Tuple , __A: Optional[Any] , __A: Tuple , __A: Tuple=True ) -> Optional[int]:
_A = ()
for resnet in self.resnets:
_A = resnet(__A , __A , deterministic=__A )
output_states += (hidden_states,)
if self.add_downsample:
_A = self.downsamplers_a(__A )
output_states += (hidden_states,)
return hidden_states, output_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = 42
A_ = 42
A_ = 0.0
A_ = 1
A_ = 1
A_ = True
A_ = False
A_ = False
A_ = False
A_ = jnp.floataa
def __A ( self: Optional[int] ) -> Any:
_A = []
_A = []
for i in range(self.num_layers ):
_A = self.in_channels if (i == self.num_layers - 1) else self.out_channels
_A = self.prev_output_channel if i == 0 else self.out_channels
_A = FlaxResnetBlockaD(
in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__A )
_A = FlaxTransformeraDModel(
in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , )
attentions.append(__A )
_A = resnets
_A = attentions
if self.add_upsample:
_A = FlaxUpsampleaD(self.out_channels , dtype=self.dtype )
def __call__( self: Tuple , __A: int , __A: Union[str, Any] , __A: Optional[int] , __A: Union[str, Any] , __A: int=True ) -> Optional[int]:
for resnet, attn in zip(self.resnets , self.attentions ):
# pop res hidden states
_A = res_hidden_states_tuple[-1]
_A = res_hidden_states_tuple[:-1]
_A = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 )
_A = resnet(__A , __A , deterministic=__A )
_A = attn(__A , __A , deterministic=__A )
if self.add_upsample:
_A = self.upsamplers_a(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = 42
A_ = 42
A_ = 0.0
A_ = 1
A_ = True
A_ = jnp.floataa
def __A ( self: str ) -> Optional[Any]:
_A = []
for i in range(self.num_layers ):
_A = self.in_channels if (i == self.num_layers - 1) else self.out_channels
_A = self.prev_output_channel if i == 0 else self.out_channels
_A = FlaxResnetBlockaD(
in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__A )
_A = resnets
if self.add_upsample:
_A = FlaxUpsampleaD(self.out_channels , dtype=self.dtype )
def __call__( self: Dict , __A: Optional[Any] , __A: int , __A: Dict , __A: str=True ) -> Optional[int]:
for resnet in self.resnets:
# pop res hidden states
_A = res_hidden_states_tuple[-1]
_A = res_hidden_states_tuple[:-1]
_A = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 )
_A = resnet(__A , __A , deterministic=__A )
if self.add_upsample:
_A = self.upsamplers_a(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = 0.0
A_ = 1
A_ = 1
A_ = False
A_ = False
A_ = jnp.floataa
def __A ( self: Any ) -> Dict:
# there is always at least one resnet
_A = [
FlaxResnetBlockaD(
in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , )
]
_A = []
for _ in range(self.num_layers ):
_A = FlaxTransformeraDModel(
in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , )
attentions.append(__A )
_A = FlaxResnetBlockaD(
in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__A )
_A = resnets
_A = attentions
def __call__( self: Optional[Any] , __A: str , __A: int , __A: Tuple , __A: List[Any]=True ) -> Optional[int]:
_A = self.resnets[0](__A , __A )
for attn, resnet in zip(self.attentions , self.resnets[1:] ):
_A = attn(__A , __A , deterministic=__A )
_A = resnet(__A , __A , deterministic=__A )
return hidden_states
| 719 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A ,_A = len(_lowercase ), len(grid[0] )
if (
min(_lowercase , _lowercase ) < 0
or row == row_length
or col == col_length
or (row, col) in visit
or grid[row][col] == 1
):
return 0
if row == row_length - 1 and col == col_length - 1:
return 1
visit.add((row, col) )
_A = 0
count += depth_first_search(_lowercase , row + 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , row - 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col + 1 , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col - 1 , _lowercase )
visit.remove((row, col) )
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
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 __A ( _lowercase , _lowercase=0.9_99 , _lowercase="cosine" , ):
'''simple docstring'''
if alpha_transform_type == "cosine":
def alpha_bar_fn(_lowercase ):
return math.cos((t + 0.0_08) / 1.0_08 * 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}""" )
_A = []
for i in range(lowerCamelCase__ ):
_A = i / num_diffusion_timesteps
_A = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(lowerCamelCase__ ) / alpha_bar_fn(lowerCamelCase__ ) , lowerCamelCase__ ) )
return torch.tensor(lowerCamelCase__ , dtype=torch.floataa )
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = [e.name for e in KarrasDiffusionSchedulers]
A_ = 2
@register_to_config
def __init__( self: Tuple , __A: int = 10_00 , __A: float = 0.00_085 , __A: float = 0.012 , __A: str = "linear" , __A: Optional[Union[np.ndarray, List[float]]] = None , __A: str = "epsilon" , __A: Optional[bool] = False , __A: Optional[bool] = False , __A: float = 1.0 , __A: str = "linspace" , __A: int = 0 , ) -> Optional[int]:
if trained_betas is not None:
_A = torch.tensor(__A , dtype=torch.floataa )
elif beta_schedule == "linear":
_A = torch.linspace(__A , __A , __A , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
_A = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , __A , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
_A = betas_for_alpha_bar(__A , alpha_transform_type='''cosine''' )
elif beta_schedule == "exp":
_A = betas_for_alpha_bar(__A , alpha_transform_type='''exp''' )
else:
raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" )
_A = 1.0 - self.betas
_A = torch.cumprod(self.alphas , dim=0 )
# set all values
self.set_timesteps(__A , __A , __A )
_A = use_karras_sigmas
def __A ( self: List[str] , __A: str , __A: Union[str, Any]=None ) -> Optional[Any]:
if schedule_timesteps is None:
_A = self.timesteps
_A = (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:
_A = 1 if len(__A ) > 1 else 0
else:
_A = timestep.cpu().item() if torch.is_tensor(__A ) else timestep
_A = self._index_counter[timestep_int]
return indices[pos].item()
@property
def __A ( self: Dict ) -> Dict:
if self.config.timestep_spacing in ["linspace", "trailing"]:
return self.sigmas.max()
return (self.sigmas.max() ** 2 + 1) ** 0.5
def __A ( self: Optional[Any] , __A: torch.FloatTensor , __A: Union[float, torch.FloatTensor] , ) -> torch.FloatTensor:
_A = self.index_for_timestep(__A )
_A = self.sigmas[step_index]
_A = sample / ((sigma**2 + 1) ** 0.5)
return sample
def __A ( self: Dict , __A: int , __A: Union[str, torch.device] = None , __A: Optional[int] = None , ) -> Optional[Any]:
_A = num_inference_steps
_A = 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":
_A = np.linspace(0 , num_train_timesteps - 1 , __A , dtype=__A )[::-1].copy()
elif self.config.timestep_spacing == "leading":
_A = 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
_A = (np.arange(0 , __A ) * step_ratio).round()[::-1].copy().astype(__A )
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
_A = 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
_A = (np.arange(__A , 0 , -step_ratio )).round().copy().astype(__A )
timesteps -= 1
else:
raise ValueError(
f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" )
_A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
_A = np.log(__A )
_A = np.interp(__A , np.arange(0 , len(__A ) ) , __A )
if self.config.use_karras_sigmas:
_A = self._convert_to_karras(in_sigmas=__A , num_inference_steps=self.num_inference_steps )
_A = np.array([self._sigma_to_t(__A , __A ) for sigma in sigmas] )
_A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
_A = torch.from_numpy(__A ).to(device=__A )
_A = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] )
_A = torch.from_numpy(__A )
_A = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] )
if str(__A ).startswith('''mps''' ):
# mps does not support float64
_A = timesteps.to(__A , dtype=torch.floataa )
else:
_A = timesteps.to(device=__A )
# empty dt and derivative
_A = None
_A = None
# for exp beta schedules, such as the one for `pipeline_shap_e.py`
# we need an index counter
_A = defaultdict(__A )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Any ) -> List[Any]:
_A = np.log(__A )
# get distribution
_A = log_sigma - log_sigmas[:, np.newaxis]
# get sigmas range
_A = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 )
_A = low_idx + 1
_A = log_sigmas[low_idx]
_A = log_sigmas[high_idx]
# interpolate sigmas
_A = (low - log_sigma) / (low - high)
_A = np.clip(__A , 0 , 1 )
# transform interpolation to time range
_A = (1 - w) * low_idx + w * high_idx
_A = t.reshape(sigma.shape )
return t
def __A ( self: List[Any] , __A: torch.FloatTensor , __A: Tuple ) -> torch.FloatTensor:
_A = in_sigmas[-1].item()
_A = in_sigmas[0].item()
_A = 7.0 # 7.0 is the value used in the paper
_A = np.linspace(0 , 1 , __A )
_A = sigma_min ** (1 / rho)
_A = sigma_max ** (1 / rho)
_A = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
return sigmas
@property
def __A ( self: Optional[Any] ) -> Tuple:
return self.dt is None
def __A ( self: List[Any] , __A: Union[torch.FloatTensor, np.ndarray] , __A: Union[float, torch.FloatTensor] , __A: Union[torch.FloatTensor, np.ndarray] , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
_A = self.index_for_timestep(__A )
# advance index counter by 1
_A = timestep.cpu().item() if torch.is_tensor(__A ) else timestep
self._index_counter[timestep_int] += 1
if self.state_in_first_order:
_A = self.sigmas[step_index]
_A = self.sigmas[step_index + 1]
else:
# 2nd order / Heun's method
_A = self.sigmas[step_index - 1]
_A = 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
_A = 0
_A = 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":
_A = sigma_hat if self.state_in_first_order else sigma_next
_A = sample - sigma_input * model_output
elif self.config.prediction_type == "v_prediction":
_A = sigma_hat if self.state_in_first_order else sigma_next
_A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
sample / (sigma_input**2 + 1)
)
elif self.config.prediction_type == "sample":
_A = model_output
else:
raise ValueError(
f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" )
if self.config.clip_sample:
_A = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range )
if self.state_in_first_order:
# 2. Convert to an ODE derivative for 1st order
_A = (sample - pred_original_sample) / sigma_hat
# 3. delta timestep
_A = sigma_next - sigma_hat
# store for 2nd order step
_A = derivative
_A = dt
_A = sample
else:
# 2. 2nd order / Heun's method
_A = (sample - pred_original_sample) / sigma_next
_A = (self.prev_derivative + derivative) / 2
# 3. take prev timestep & sample
_A = self.dt
_A = self.sample
# free dt and derivative
# Note, this puts the scheduler in "first order mode"
_A = None
_A = None
_A = None
_A = sample + derivative * dt
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Tuple , __A: torch.FloatTensor , __A: torch.FloatTensor , __A: torch.FloatTensor , ) -> torch.FloatTensor:
_A = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype )
if original_samples.device.type == "mps" and torch.is_floating_point(__A ):
# mps does not support float64
_A = self.timesteps.to(original_samples.device , dtype=torch.floataa )
_A = timesteps.to(original_samples.device , dtype=torch.floataa )
else:
_A = self.timesteps.to(original_samples.device )
_A = timesteps.to(original_samples.device )
_A = [self.index_for_timestep(__A , __A ) for t in timesteps]
_A = sigmas[step_indices].flatten()
while len(sigma.shape ) < len(original_samples.shape ):
_A = sigma.unsqueeze(-1 )
_A = original_samples + noise * sigma
return noisy_samples
def __len__( self: str ) -> List[str]:
return self.config.num_train_timesteps
| 720 |
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
__A = NewType('DataClass', Any)
__A = NewType('DataClassType', Any)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , _lowercase ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError(
f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" )
def __A ( _lowercase ):
'''simple docstring'''
_A = {str(_lowercase ): choice for choice in choices}
return lambda _lowercase : str_to_choice.get(_lowercase , _lowercase )
def __A ( *,
_lowercase = None , _lowercase = None , _lowercase = dataclasses.MISSING , _lowercase = dataclasses.MISSING , _lowercase = None , **_lowercase , ):
'''simple docstring'''
if metadata is None:
# Important, don't use as default param in function signature because dict is mutable and shared across function calls
_A = {}
if aliases is not None:
_A = aliases
if help is not None:
_A = help
return dataclasses.field(metadata=_lowercase , default=_lowercase , default_factory=_lowercase , **_lowercase )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = 42
def __init__( self: Optional[Any] , __A: Union[DataClassType, Iterable[DataClassType]] , **__A: List[Any] ) -> str:
# To make the default appear when using --help
if "formatter_class" not in kwargs:
_A = ArgumentDefaultsHelpFormatter
super().__init__(**__A )
if dataclasses.is_dataclass(__A ):
_A = [dataclass_types]
_A = list(__A )
for dtype in self.dataclass_types:
self._add_dataclass_arguments(__A )
@staticmethod
def __A ( __A: ArgumentParser , __A: dataclasses.Field ) -> str:
_A = f"""--{field.name}"""
_A = field.metadata.copy()
# field.metadata is not used at all by Data Classes,
# it is provided as a third-party extension mechanism.
if isinstance(field.type , __A ):
raise RuntimeError(
'''Unresolved type detected, which should have been done with the help of '''
'''`typing.get_type_hints` method by default''' )
_A = kwargs.pop('''aliases''' , [] )
if isinstance(__A , __A ):
_A = [aliases]
_A = getattr(field.type , '''__origin__''' , field.type )
if origin_type is Union or (hasattr(__A , '''UnionType''' ) and isinstance(__A , types.UnionType )):
if str not in field.type.__args__ and (
len(field.type.__args__ ) != 2 or type(__A ) not in field.type.__args__
):
raise ValueError(
'''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
''' the argument parser only supports one type per argument.'''
f""" Problem encountered in field '{field.name}'.""" )
if type(__A ) not in field.type.__args__:
# filter `str` in Union
_A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
_A = getattr(field.type , '''__origin__''' , field.type )
elif bool not in field.type.__args__:
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
_A = (
field.type.__args__[0] if isinstance(__A , field.type.__args__[1] ) else field.type.__args__[1]
)
_A = getattr(field.type , '''__origin__''' , field.type )
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
_A = {}
if origin_type is Literal or (isinstance(field.type , __A ) and issubclass(field.type , __A )):
if origin_type is Literal:
_A = field.type.__args__
else:
_A = [x.value for x in field.type]
_A = make_choice_type_function(kwargs['''choices'''] )
if field.default is not dataclasses.MISSING:
_A = field.default
else:
_A = True
elif field.type is bool or field.type == Optional[bool]:
# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
_A = copy(__A )
# Hack because type=bool in argparse does not behave as we want.
_A = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
_A = False if field.default is dataclasses.MISSING else field.default
# This is the value that will get picked if we don't include --field_name in any way
_A = default
# This tells argparse we accept 0 or 1 value after --field_name
_A = '''?'''
# This is the value that will get picked if we do --field_name (without value)
_A = True
elif isclass(__A ) and issubclass(__A , __A ):
_A = field.type.__args__[0]
_A = '''+'''
if field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
elif field.default is dataclasses.MISSING:
_A = True
else:
_A = field.type
if field.default is not dataclasses.MISSING:
_A = field.default
elif field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
else:
_A = True
parser.add_argument(__A , *__A , **__A )
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need those changes/additional keys.
if field.default is True and (field.type is bool or field.type == Optional[bool]):
_A = False
parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__A )
def __A ( self: Dict , __A: DataClassType ) -> List[Any]:
if hasattr(__A , '''_argument_group_name''' ):
_A = self.add_argument_group(dtype._argument_group_name )
else:
_A = self
try:
_A = get_type_hints(__A )
except NameError:
raise RuntimeError(
f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
'''removing line of `from __future__ import annotations` which opts in Postponed '''
'''Evaluation of Annotations (PEP 563)''' )
except TypeError as ex:
# Remove this block when we drop Python 3.9 support
if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__A ):
_A = '''.'''.join(map(__A , sys.version_info[:3] ) )
raise RuntimeError(
f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
'''line of `from __future__ import annotations` which opts in union types as '''
'''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
'''support Python versions that lower than 3.10, you need to use '''
'''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
'''`X | None`.''' ) from ex
raise
for field in dataclasses.fields(__A ):
if not field.init:
continue
_A = type_hints[field.name]
self._parse_dataclass_field(__A , __A )
def __A ( self: int , __A: Any=None , __A: int=False , __A: Any=True , __A: Optional[Any]=None , __A: Any=None , ) -> Tuple[DataClass, ...]:
if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )):
_A = []
if args_filename:
args_files.append(Path(__A ) )
elif look_for_args_file and len(sys.argv ):
args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) )
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
_A = ArgumentParser()
args_file_parser.add_argument(__A , type=__A , action='''append''' )
# Use only remaining args for further parsing (remove the args_file_flag)
_A ,_A = args_file_parser.parse_known_args(args=__A )
_A = vars(__A ).get(args_file_flag.lstrip('''-''' ) , __A )
if cmd_args_file_paths:
args_files.extend([Path(__A ) for p in cmd_args_file_paths] )
_A = []
for args_file in args_files:
if args_file.exists():
file_args += args_file.read_text().split()
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
_A = file_args + args if args is not None else file_args + sys.argv[1:]
_A ,_A = self.parse_known_args(args=__A )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in vars(__A ).items() if k in keys}
for k in keys:
delattr(__A , __A )
_A = dtype(**__A )
outputs.append(__A )
if len(namespace.__dict__ ) > 0:
# additional namespace.
outputs.append(__A )
if return_remaining_strings:
return (*outputs, remaining_args)
else:
if remaining_args:
raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" )
return (*outputs,)
def __A ( self: Tuple , __A: Dict[str, Any] , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = set(args.keys() )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in args.items() if k in keys}
unused_keys.difference_update(inputs.keys() )
_A = dtype(**__A )
outputs.append(__A )
if not allow_extra_keys and unused_keys:
raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__A )}""" )
return tuple(__A )
def __A ( self: Tuple , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
with open(Path(__A ) , encoding='''utf-8''' ) as open_json_file:
_A = json.loads(open_json_file.read() )
_A = self.parse_dict(__A , allow_extra_keys=__A )
return tuple(__A )
def __A ( self: List[Any] , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = self.parse_dict(yaml.safe_load(Path(__A ).read_text() ) , allow_extra_keys=__A )
return tuple(__A )
| 62 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case__ ):
"""simple docstring"""
A_ = "mra"
def __init__( self: int , __A: int=5_02_65 , __A: Tuple=7_68 , __A: List[Any]=12 , __A: Tuple=12 , __A: int=30_72 , __A: Tuple="gelu" , __A: Dict=0.1 , __A: Any=0.1 , __A: List[Any]=5_12 , __A: Optional[Any]=1 , __A: List[Any]=0.02 , __A: Dict=1e-5 , __A: Optional[int]="absolute" , __A: List[str]=4 , __A: int="full" , __A: Tuple=0 , __A: Optional[Any]=0 , __A: Optional[Any]=1 , __A: str=0 , __A: Optional[int]=2 , **__A: int , ) -> str:
super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
_A = vocab_size
_A = max_position_embeddings
_A = hidden_size
_A = num_hidden_layers
_A = num_attention_heads
_A = intermediate_size
_A = hidden_act
_A = hidden_dropout_prob
_A = attention_probs_dropout_prob
_A = initializer_range
_A = type_vocab_size
_A = layer_norm_eps
_A = position_embedding_type
_A = block_per_row
_A = approx_mode
_A = initial_prior_first_n_blocks
_A = initial_prior_diagonal_n_blocks
| 721 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: Union[str, Any] , __A: int=2 , __A: List[str]=True , __A: List[Any]=False , __A: Union[str, Any]=10 , __A: Optional[int]=3 , __A: List[Any]=32 * 4 , __A: Dict=32 * 6 , __A: Optional[Any]=4 , __A: Any=32 , ) -> str:
_A = parent
_A = batch_size
_A = is_training
_A = use_auxiliary_loss
_A = num_queries
_A = num_channels
_A = min_size
_A = max_size
_A = num_labels
_A = mask_feature_size
def __A ( self: Dict ) -> Optional[int]:
_A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
__A )
_A = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A )
_A = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5
).float()
_A = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long()
_A = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __A ( self: Optional[Any] ) -> Tuple:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __A ( self: Dict ) -> Tuple:
_A ,_A ,_A ,_A ,_A = self.prepare_config_and_inputs()
_A = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: Dict ) -> int:
_A = output.encoder_hidden_states
_A = output.pixel_decoder_hidden_states
_A = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , config.decoder_config.decoder_layers )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Any , __A: Dict=False ) -> Any:
with torch.no_grad():
_A = MaskFormerModel(config=__A )
model.to(__A )
model.eval()
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A , output_hidden_states=__A )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(__A , __A )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Union[str, Any] , __A: Union[str, Any] , __A: List[Any] ) -> int:
_A = MaskFormerForInstanceSegmentation(config=__A )
model.to(__A )
model.eval()
def comm_check_on_output(__A: int ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A )
comm_check_on_output(__A )
_A = model(
pixel_values=__A , pixel_mask=__A , mask_labels=__A , class_labels=__A )
comm_check_on_output(__A )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
A_ = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
A_ = False
A_ = False
A_ = False
A_ = False
def __A ( self: int ) -> Tuple:
_A = MaskFormerModelTester(self )
_A = ConfigTester(self , config_class=__A , has_text_modality=__A )
def __A ( self: List[Any] ) -> Dict:
self.config_tester.run_common_tests()
def __A ( self: Optional[Any] ) -> int:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Dict ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__A )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def __A ( self: int ) -> Tuple:
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def __A ( self: List[Any] ) -> Any:
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def __A ( self: Union[str, Any] ) -> Optional[int]:
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def __A ( self: int ) -> List[str]:
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def __A ( self: Union[str, Any] ) -> List[Any]:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: List[Any] ) -> Any:
pass
def __A ( self: Dict ) -> Optional[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A )
_A = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_A = [*signature.parameters.keys()]
_A = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __A )
@slow
def __A ( self: int ) -> Optional[Any]:
for model_name in ["facebook/maskformer-swin-small-coco"]:
_A = MaskFormerModel.from_pretrained(__A )
self.assertIsNotNone(__A )
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = (self.model_tester.min_size,) * 2
_A = {
'''pixel_values''': torch.randn((2, 3, *size) , device=__A ),
'''mask_labels''': torch.randn((2, 10, *size) , device=__A ),
'''class_labels''': torch.zeros(2 , 10 , device=__A ).long(),
}
_A = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__A )
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
def __A ( self: Optional[Any] ) -> List[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Any ) -> Tuple:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A ).to(__A )
_A = model(**__A , output_attentions=__A )
self.assertTrue(outputs.attentions is not None )
def __A ( self: Dict ) -> Union[str, Any]:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A ).loss
loss.backward()
def __A ( self: Tuple ) -> Optional[Any]:
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = True
_A = True
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A )
_A = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
_A = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
_A = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
_A = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=__A )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__A = 1e-4
def __A ( ):
'''simple docstring'''
_A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self: Union[str, Any] ) -> Optional[int]:
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def __A ( self: List[Any] ) -> Any:
_A = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(__A )
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
_A = torch.tensor(
[[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Dict ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [
[-1.3_737_124, -1.7_724_937, -1.9_364_233],
[-1.5_977_281, -1.9_867_939, -2.1_523_695],
[-1.5_795_398, -1.9_269_832, -2.093_942],
]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: List[Any] ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Optional[Any] ) -> str:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors='''pt''' , )
_A = inputs['''pixel_values'''].to(__A )
_A = [el.to(__A ) for el in inputs['''mask_labels''']]
_A = [el.to(__A ) for el in inputs['''class_labels''']]
with torch.no_grad():
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
| 62 | 0 |
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __init__( self: Optional[Any] , __A: Dict , __A: List[str]=13 , __A: Any=3 , __A: List[Any]=2_24 , __A: List[str]=30 , __A: List[str]=4_00 , __A: Optional[int]=True , __A: Optional[Any]=None , __A: Union[str, Any]=True , __A: List[str]=[0.5, 0.5, 0.5] , __A: Optional[Any]=[0.5, 0.5, 0.5] , ) -> Optional[int]:
_A = size if size is not None else {'''height''': 18, '''width''': 18}
_A = parent
_A = batch_size
_A = num_channels
_A = image_size
_A = min_resolution
_A = max_resolution
_A = do_resize
_A = size
_A = do_normalize
_A = image_mean
_A = image_std
def __A ( self: Any ) -> Optional[int]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = ViTImageProcessor if is_vision_available() else None
def __A ( self: List[Any] ) -> Optional[int]:
_A = EfficientFormerImageProcessorTester(self )
@property
def __A ( self: int ) -> Tuple:
return self.image_proc_tester.prepare_image_processor_dict()
def __A ( self: Union[str, Any] ) -> str:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , '''image_mean''' ) )
self.assertTrue(hasattr(__A , '''image_std''' ) )
self.assertTrue(hasattr(__A , '''do_normalize''' ) )
self.assertTrue(hasattr(__A , '''do_resize''' ) )
self.assertTrue(hasattr(__A , '''size''' ) )
def __A ( self: List[Any] ) -> int:
pass
def __A ( self: Optional[Any] ) -> Tuple:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_proc_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_A = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_proc_tester.num_channels,
self.image_proc_tester.size['''height'''],
self.image_proc_tester.size['''width'''],
) , )
# Test batched
_A = image_processor(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_proc_tester.batch_size,
self.image_proc_tester.num_channels,
self.image_proc_tester.size['''height'''],
self.image_proc_tester.size['''width'''],
) , )
def __A ( self: List[Any] ) -> Optional[int]:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_A = prepare_image_inputs(self.image_proc_tester , equal_resolution=__A , numpify=__A )
for image in image_inputs:
self.assertIsInstance(__A , np.ndarray )
# Test not batched input
_A = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_proc_tester.num_channels,
self.image_proc_tester.size['''height'''],
self.image_proc_tester.size['''width'''],
) , )
# Test batched
_A = image_processor(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_proc_tester.batch_size,
self.image_proc_tester.num_channels,
self.image_proc_tester.size['''height'''],
self.image_proc_tester.size['''width'''],
) , )
def __A ( self: List[Any] ) -> Any:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_A = prepare_image_inputs(self.image_proc_tester , equal_resolution=__A , torchify=__A )
for image in image_inputs:
self.assertIsInstance(__A , torch.Tensor )
# Test not batched input
_A = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_proc_tester.num_channels,
self.image_proc_tester.size['''height'''],
self.image_proc_tester.size['''width'''],
) , )
# Test batched
_A = image_processor(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_proc_tester.batch_size,
self.image_proc_tester.num_channels,
self.image_proc_tester.size['''height'''],
self.image_proc_tester.size['''width'''],
) , )
| 700 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Optional[int] , __A: Optional[Any] ) -> str:
_A = question_encoder
_A = generator
_A = self.question_encoder
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Dict:
if os.path.isfile(__A ):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(__A , exist_ok=__A )
_A = os.path.join(__A , '''question_encoder_tokenizer''' )
_A = os.path.join(__A , '''generator_tokenizer''' )
self.question_encoder.save_pretrained(__A )
self.generator.save_pretrained(__A )
@classmethod
def __A ( cls: Optional[Any] , __A: List[str] , **__A: int ) -> Any:
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
_A = kwargs.pop('''config''' , __A )
if config is None:
_A = RagConfig.from_pretrained(__A )
_A = AutoTokenizer.from_pretrained(
__A , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' )
_A = AutoTokenizer.from_pretrained(
__A , config=config.generator , subfolder='''generator_tokenizer''' )
return cls(question_encoder=__A , generator=__A )
def __call__( self: int , *__A: Optional[int] , **__A: List[str] ) -> int:
return self.current_tokenizer(*__A , **__A )
def __A ( self: Dict , *__A: List[str] , **__A: List[str] ) -> Dict:
return self.generator.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Tuple , **__A: List[str] ) -> Tuple:
return self.generator.decode(*__A , **__A )
def __A ( self: Dict ) -> List[str]:
_A = self.question_encoder
def __A ( self: Union[str, Any] ) -> int:
_A = self.generator
def __A ( self: Dict , __A: List[str] , __A: Optional[List[str]] = None , __A: Optional[int] = None , __A: Optional[int] = None , __A: str = "longest" , __A: str = None , __A: bool = True , **__A: Tuple , ) -> BatchEncoding:
warnings.warn(
'''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
'''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
'''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
'''details''' , __A , )
if max_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
__A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , )
_A = labels['''input_ids''']
return model_inputs
| 62 | 0 |
__A = {
'Pillow': 'Pillow<10.0.0',
'accelerate': 'accelerate>=0.20.3',
'av': 'av==9.2.0',
'beautifulsoup4': 'beautifulsoup4',
'black': 'black~=23.1',
'codecarbon': 'codecarbon==1.2.0',
'cookiecutter': 'cookiecutter==1.7.3',
'dataclasses': 'dataclasses',
'datasets': 'datasets!=2.5.0',
'decord': 'decord==0.6.0',
'deepspeed': 'deepspeed>=0.9.3',
'diffusers': 'diffusers',
'dill': 'dill<0.3.5',
'evaluate': 'evaluate>=0.2.0',
'fairscale': 'fairscale>0.3',
'faiss-cpu': 'faiss-cpu',
'fastapi': 'fastapi',
'filelock': 'filelock',
'flax': 'flax>=0.4.1,<=0.7.0',
'ftfy': 'ftfy',
'fugashi': 'fugashi>=1.0',
'GitPython': 'GitPython<3.1.19',
'hf-doc-builder': 'hf-doc-builder>=0.3.0',
'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0',
'importlib_metadata': 'importlib_metadata',
'ipadic': 'ipadic>=1.0.0,<2.0',
'isort': 'isort>=5.5.4',
'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13',
'jaxlib': 'jaxlib>=0.1.65,<=0.4.13',
'jieba': 'jieba',
'kenlm': 'kenlm',
'keras-nlp': 'keras-nlp>=0.3.1',
'librosa': 'librosa',
'nltk': 'nltk',
'natten': 'natten>=0.14.6',
'numpy': 'numpy>=1.17',
'onnxconverter-common': 'onnxconverter-common',
'onnxruntime-tools': 'onnxruntime-tools>=1.4.2',
'onnxruntime': 'onnxruntime>=1.4.0',
'opencv-python': 'opencv-python',
'optuna': 'optuna',
'optax': 'optax>=0.0.8,<=0.1.4',
'packaging': 'packaging>=20.0',
'parameterized': 'parameterized',
'phonemizer': 'phonemizer',
'protobuf': 'protobuf',
'psutil': 'psutil',
'pyyaml': 'pyyaml>=5.1',
'pydantic': 'pydantic<2',
'pytest': 'pytest>=7.2.0',
'pytest-timeout': 'pytest-timeout',
'pytest-xdist': 'pytest-xdist',
'python': 'python>=3.8.0',
'ray[tune]': 'ray[tune]',
'regex': 'regex!=2019.12.17',
'requests': 'requests',
'rhoknp': 'rhoknp>=1.1.0,<1.3.1',
'rjieba': 'rjieba',
'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1',
'ruff': 'ruff>=0.0.241,<=0.0.259',
'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0',
'sacremoses': 'sacremoses',
'safetensors': 'safetensors>=0.3.1',
'sagemaker': 'sagemaker>=2.31.0',
'scikit-learn': 'scikit-learn',
'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
'sigopt': 'sigopt',
'starlette': 'starlette',
'sudachipy': 'sudachipy>=0.6.6',
'sudachidict_core': 'sudachidict_core>=20220729',
'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14',
'tensorflow': 'tensorflow>=2.6,<2.14',
'tensorflow-text': 'tensorflow-text<2.14',
'tf2onnx': 'tf2onnx',
'timeout-decorator': 'timeout-decorator',
'timm': 'timm',
'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14',
'torch': 'torch>=1.9,!=1.12.0',
'torchaudio': 'torchaudio',
'torchvision': 'torchvision',
'pyctcdecode': 'pyctcdecode>=0.4.0',
'tqdm': 'tqdm>=4.27',
'unidic': 'unidic>=1.0.2',
'unidic_lite': 'unidic_lite>=1.0.7',
'urllib3': 'urllib3<2.0.0',
'uvicorn': 'uvicorn',
}
| 701 |
from __future__ import annotations
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ): # noqa: E741
'''simple docstring'''
while r - l > 1:
_A = (l + r) // 2
if v[m] >= key:
_A = m
else:
_A = m # noqa: E741
return r
def __A ( _lowercase ):
'''simple docstring'''
if len(_lowercase ) == 0:
return 0
_A = [0] * len(_lowercase )
_A = 1
_A = v[0]
for i in range(1 , len(_lowercase ) ):
if v[i] < tail[0]:
_A = v[i]
elif v[i] > tail[length - 1]:
_A = v[i]
length += 1
else:
_A = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
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 SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Union[str, Any] , __A: Dict , __A: Union[str, Any]=sys.maxsize ) -> Tuple:
_A = '''bilinear'''
_A = max_size
_A = short_edge_length
def __call__( self: Dict , __A: Optional[int] ) -> Any:
_A = []
for img in imgs:
_A ,_A = img.shape[:2]
# later: provide list and randomly choose index for resize
_A = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 )
if size == 0:
return img
_A = size * 1.0 / min(__A , __A )
if h < w:
_A ,_A = size, scale * w
else:
_A ,_A = scale * h, size
if max(__A , __A ) > self.max_size:
_A = self.max_size * 1.0 / max(__A , __A )
_A = newh * scale
_A = neww * scale
_A = int(neww + 0.5 )
_A = int(newh + 0.5 )
if img.dtype == np.uinta:
_A = Image.fromarray(__A )
_A = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR )
_A = np.asarray(__A )
else:
_A = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw
_A = nn.functional.interpolate(
__A , (newh, neww) , mode=self.interp_method , align_corners=__A ).squeeze(0 )
img_augs.append(__A )
return img_augs
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Tuple , __A: int ) -> List[str]:
_A = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST )
_A = cfg.INPUT.FORMAT
_A = cfg.SIZE_DIVISIBILITY
_A = cfg.PAD_VALUE
_A = cfg.INPUT.MAX_SIZE_TEST
_A = cfg.MODEL.DEVICE
_A = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 )
_A = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 )
_A = lambda __A : (x - self.pixel_mean) / self.pixel_std
def __A ( self: List[Any] , __A: str ) -> Union[str, Any]:
_A = tuple(max(__A ) for s in zip(*[img.shape for img in images] ) )
_A = [im.shape[-2:] for im in images]
_A = [
nn.functional.pad(
__A , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , )
for size, im in zip(__A , __A )
]
return torch.stack(__A ), torch.tensor(__A )
def __call__( self: int , __A: Dict , __A: List[str]=False ) -> List[str]:
with torch.no_grad():
if not isinstance(__A , __A ):
_A = [images]
if single_image:
assert len(__A ) == 1
for i in range(len(__A ) ):
if isinstance(images[i] , torch.Tensor ):
images.insert(__A , images.pop(__A ).to(self.device ).float() )
elif not isinstance(images[i] , torch.Tensor ):
images.insert(
__A , torch.as_tensor(img_tensorize(images.pop(__A ) , input_format=self.input_format ) )
.to(self.device )
.float() , )
# resize smallest edge
_A = torch.tensor([im.shape[:2] for im in images] )
_A = self.aug(__A )
# 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
_A = [self.normalizer(__A ) for x in images]
# now pad them to do the following operations
_A ,_A = self.pad(__A )
# Normalize
if self.size_divisibility > 0:
raise NotImplementedError()
# pad
_A = torch.true_divide(__A , __A )
if single_image:
return images[0], sizes[0], scales_yx[0]
else:
return images, sizes, scales_yx
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
boxes[:, 0::2] *= scale_yx[:, 1]
boxes[:, 1::2] *= scale_yx[:, 0]
return boxes
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
assert torch.isfinite(_lowercase ).all(), "Box tensor contains infinite or NaN!"
_A ,_A = box_size
tensor[:, 0].clamp_(min=0 , max=_lowercase )
tensor[:, 1].clamp_(min=0 , max=_lowercase )
tensor[:, 2].clamp_(min=0 , max=_lowercase )
tensor[:, 3].clamp_(min=0 , max=_lowercase )
| 702 |
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
__A = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "sequence-classification"
def __init__( self: str , __A: Union[str, Any] ) -> List[str]:
if type(__A ) == dict:
_A = Namespace(**__A )
_A = glue_output_modes[hparams.task]
_A = glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def __A ( self: Optional[Any] , **__A: Union[str, Any] ) -> Optional[int]:
return self.model(**__A )
def __A ( self: Any , __A: Union[str, Any] , __A: int ) -> Optional[Any]:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A = outputs[0]
_A = self.trainer.lr_schedulers[0]['''scheduler''']
_A = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def __A ( self: List[str] ) -> Dict:
_A = self.hparams
_A = processors[args.task]()
_A = processor.get_labels()
for mode in ["train", "dev"]:
_A = self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('''Loading features from cached file %s''' , __A )
else:
logger.info('''Creating features from dataset file at %s''' , args.data_dir )
_A = (
processor.get_dev_examples(args.data_dir )
if mode == '''dev'''
else processor.get_train_examples(args.data_dir )
)
_A = convert_examples_to_features(
__A , 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''' , __A )
torch.save(__A , __A )
def __A ( self: List[str] , __A: str , __A: int , __A: bool = False ) -> DataLoader:
_A = '''dev''' if mode == '''test''' else mode
_A = self._feature_file(__A )
logger.info('''Loading features from cached file %s''' , __A )
_A = torch.load(__A )
_A = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_A = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_A = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_A = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_A = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def __A ( self: List[str] , __A: str , __A: Tuple ) -> str:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A ,_A = outputs[:2]
_A = logits.detach().cpu().numpy()
_A = inputs['''labels'''].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __A ( self: str , __A: Dict ) -> tuple:
_A = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item()
_A = np.concatenate([x['''pred'''] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_A = np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_A = np.squeeze(__A )
_A = np.concatenate([x['''target'''] for x in outputs] , axis=0 )
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_A = dict(results.items() )
_A = results
return ret, preds_list, out_label_list
def __A ( self: Any , __A: list ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = ret['''log''']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __A ( self: int , __A: Union[str, Any] ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = 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 ( __A: Optional[Any] , __A: Optional[Any] ) -> Optional[Any]:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'''--max_seq_length''' , default=1_28 , type=__A , 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=__A , required=__A , help='''The GLUE task to run''' , )
parser.add_argument(
'''--gpus''' , default=0 , type=__A , 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 __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser()
add_generic_args(_lowercase , os.getcwd() )
_A = GLUETransformer.add_model_specific_args(_lowercase , os.getcwd() )
_A = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_A = os.path.join(
'''./results''' , f"""{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}""" , )
os.makedirs(args.output_dir )
_A = GLUETransformer(_lowercase )
_A = generic_train(_lowercase , _lowercase )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_A = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=_lowercase ) )
_A = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(_lowercase )
if __name__ == "__main__":
main()
| 62 | 0 |
import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field
import torch
from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging
__A = logging.get_logger(__name__)
def __A ( ):
'''simple docstring'''
_A = os.getenv('''SM_HP_MP_PARAMETERS''' , '''{}''' )
try:
# Parse it and check the field "partitions" is included, it is required for model parallel.
_A = json.loads(_lowercase )
if "partitions" not in smp_options:
return False
except json.JSONDecodeError:
return False
# Get the sagemaker specific framework parameters from mpi_options variable.
_A = os.getenv('''SM_FRAMEWORK_PARAMS''' , '''{}''' )
try:
# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
_A = json.loads(_lowercase )
if not mpi_options.get('''sagemaker_mpi_enabled''' , _lowercase ):
return False
except json.JSONDecodeError:
return False
# Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec('''smdistributed''' ) is not None
if is_sagemaker_model_parallel_available():
import smdistributed.modelparallel.torch as smp
smp.init()
@dataclass
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
lowerCAmelCase_ = field(
default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , )
def __A ( self: Dict ) -> Tuple:
super().__post_init__()
warnings.warn(
'''`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use '''
'''`TrainingArguments` instead.''' , __A , )
@cached_property
def __A ( self: Any ) -> "torch.device":
logger.info('''PyTorch: setting up devices''' )
if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
logger.warning(
'''torch.distributed process group is initialized, but local_rank == -1. '''
'''In order to use Torch DDP, launch your script with `python -m torch.distributed.launch''' )
if self.no_cuda:
_A = torch.device('''cpu''' )
_A = 0
elif is_sagemaker_model_parallel_available():
_A = smp.local_rank()
_A = torch.device('''cuda''' , __A )
_A = 1
elif is_sagemaker_dp_enabled():
import smdistributed.dataparallel.torch.torch_smddp # noqa: F401
torch.distributed.init_process_group(backend='''smddp''' , timeout=self.ddp_timeout_delta )
_A = int(os.getenv('''SMDATAPARALLEL_LOCAL_RANK''' ) )
_A = torch.device('''cuda''' , self.local_rank )
_A = 1
elif self.local_rank == -1:
# if n_gpu is > 1 we'll use nn.DataParallel.
# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
# Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
# trigger an error that a device index is missing. Index 0 takes into account the
# GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
# will use the first GPU in that env, i.e. GPU#1
_A = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' )
# Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
# the default value.
_A = torch.cuda.device_count()
else:
# Here, we'll use torch.distributed.
# Initializes the distributed backend which will take care of synchronizing nodes/GPUs
if not torch.distributed.is_initialized():
torch.distributed.init_process_group(backend='''nccl''' , timeout=self.ddp_timeout_delta )
_A = torch.device('''cuda''' , self.local_rank )
_A = 1
if device.type == "cuda":
torch.cuda.set_device(__A )
return device
@property
def __A ( self: List[Any] ) -> Tuple:
if is_sagemaker_model_parallel_available():
return smp.dp_size()
return super().world_size
@property
def __A ( self: Dict ) -> Any:
return not is_sagemaker_model_parallel_available()
@property
def __A ( self: int ) -> Optional[Any]:
return False
| 703 |
from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def __A ( _lowercase = "" ):
'''simple docstring'''
_A = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250'''
_A = BeautifulSoup(requests.get(_lowercase ).text , '''html.parser''' )
_A = soup.find_all('''td''' , attrs='''titleColumn''' )
_A = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' )
return {
title.a.text: float(rating.strong.text )
for title, rating in zip(_lowercase , _lowercase )
}
def __A ( _lowercase = "IMDb_Top_250_Movies.csv" ):
'''simple docstring'''
_A = get_imdb_top_aaa_movies()
with open(_lowercase , '''w''' , newline='''''' ) as out_file:
_A = csv.writer(_lowercase )
writer.writerow(['''Movie title''', '''IMDb rating'''] )
for title, rating in movies.items():
writer.writerow([title, rating] )
if __name__ == "__main__":
write_movies()
| 62 | 0 |
import baseaa
def __A ( _lowercase ):
'''simple docstring'''
return baseaa.aaaencode(string.encode('''utf-8''' ) )
def __A ( _lowercase ):
'''simple docstring'''
return baseaa.aaadecode(_lowercase ).decode('''utf-8''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 704 |
import json
import os
import unittest
from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
VOCAB_FILES_NAMES,
BlenderbotSmallTokenizer,
)
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = BlenderbotSmallTokenizer
A_ = False
def __A ( self: List[str] ) -> int:
super().setUp()
_A = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__''']
_A = dict(zip(__A , range(len(__A ) ) ) )
_A = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', '''''']
_A = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''}
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_A = 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 __A ( self: str , **__A: Optional[Any] ) -> Dict:
kwargs.update(self.special_tokens_map )
return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__A )
def __A ( self: str , __A: List[str] ) -> int:
_A = '''adapt act apte'''
_A = '''adapt act apte'''
return input_text, output_text
def __A ( self: Union[str, Any] ) -> Any:
_A = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_A = '''adapt act apte'''
_A = ['''adapt''', '''act''', '''ap@@''', '''te''']
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , __A )
_A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
_A = [0, 1, 2, 3, 4, 5]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
def __A ( self: Any ) -> List[str]:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
assert tok('''sam''' ).input_ids == [13_84]
_A = '''I am a small frog.'''
_A = tok([src_text] , padding=__A , truncation=__A )['''input_ids''']
_A = tok.batch_decode(__A , skip_special_tokens=__A , clean_up_tokenization_spaces=__A )[0]
assert src_text != decoded # I wish it did!
assert decoded == "i am a small frog ."
def __A ( self: Any ) -> int:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
_A = '''I am a small frog .'''
_A = '''.'''
_A = tok(__A )['''input_ids''']
_A = tok(__A )['''input_ids''']
assert encoded[-1] == encoded_dot[0]
| 62 | 0 |
def __A ( _lowercase ):
'''simple docstring'''
if not all(char in '''01''' for char in bin_string ):
raise ValueError('''Non-binary value was passed to the function''' )
if not bin_string:
raise ValueError('''Empty string was passed to the function''' )
_A = ''''''
while len(_lowercase ) % 3 != 0:
_A = '''0''' + bin_string
_A = [
bin_string[index : index + 3]
for index in range(len(_lowercase ) )
if index % 3 == 0
]
for bin_group in bin_string_in_3_list:
_A = 0
for index, val in enumerate(_lowercase ):
oct_val += int(2 ** (2 - index) * int(_lowercase ) )
oct_string += str(_lowercase )
return oct_string
if __name__ == "__main__":
from doctest import testmod
testmod()
| 705 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json',
'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "roberta"
def __init__( self: Dict , __A: int=5_02_65 , __A: Union[str, Any]=7_68 , __A: Union[str, Any]=12 , __A: str=12 , __A: int=30_72 , __A: str="gelu" , __A: Union[str, Any]=0.1 , __A: int=0.1 , __A: Optional[int]=5_12 , __A: Union[str, Any]=2 , __A: str=0.02 , __A: str=1e-12 , __A: Any=1 , __A: str=0 , __A: Any=2 , __A: Optional[int]="absolute" , __A: Optional[Any]=True , __A: Union[str, Any]=None , **__A: List[str] , ) -> Dict:
super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
_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 SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
def __A ( self: Dict ) -> Mapping[str, Mapping[int, str]]:
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),
] )
| 62 | 0 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_roformer import RoFormerTokenizer
from .tokenization_utils import JiebaPreTokenizer
__A = logging.get_logger(__name__)
__A = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}
__A = {
'vocab_file': {
'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt',
'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt',
'junnyu/roformer_chinese_char_small': (
'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt'
),
'junnyu/roformer_chinese_char_base': (
'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt'
),
'junnyu/roformer_small_discriminator': (
'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt'
),
'junnyu/roformer_small_generator': (
'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt'
),
}
}
__A = {
'junnyu/roformer_chinese_small': 1536,
'junnyu/roformer_chinese_base': 1536,
'junnyu/roformer_chinese_char_small': 512,
'junnyu/roformer_chinese_char_base': 512,
'junnyu/roformer_small_discriminator': 128,
'junnyu/roformer_small_generator': 128,
}
__A = {
'junnyu/roformer_chinese_small': {'do_lower_case': True},
'junnyu/roformer_chinese_base': {'do_lower_case': True},
'junnyu/roformer_chinese_char_small': {'do_lower_case': True},
'junnyu/roformer_chinese_char_base': {'do_lower_case': True},
'junnyu/roformer_small_discriminator': {'do_lower_case': True},
'junnyu/roformer_small_generator': {'do_lower_case': True},
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = VOCAB_FILES_NAMES
A_ = PRETRAINED_VOCAB_FILES_MAP
A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A_ = PRETRAINED_INIT_CONFIGURATION
A_ = RoFormerTokenizer
def __init__( self: Any , __A: Union[str, Any]=None , __A: Dict=None , __A: Dict=True , __A: Union[str, Any]="[UNK]" , __A: List[Any]="[SEP]" , __A: List[str]="[PAD]" , __A: List[str]="[CLS]" , __A: List[str]="[MASK]" , __A: int=True , __A: List[Any]=None , **__A: int , ) -> int:
super().__init__(
__A , tokenizer_file=__A , do_lower_case=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , tokenize_chinese_chars=__A , strip_accents=__A , **__A , )
_A = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
pre_tok_state.get('''lowercase''' , __A ) != do_lower_case
or pre_tok_state.get('''strip_accents''' , __A ) != strip_accents
):
_A = getattr(__A , pre_tok_state.pop('''type''' ) )
_A = do_lower_case
_A = strip_accents
_A = pre_tok_class(**__A )
_A = do_lower_case
def __getstate__( self: Union[str, Any] ) -> str:
_A = self.__dict__.copy()
_A = BertPreTokenizer()
return state
def __setstate__( self: Union[str, Any] , __A: Union[str, Any] ) -> Optional[int]:
_A = d
_A = self.__dict__['''_tokenizer'''].get_vocab()
_A = PreTokenizer.custom(JiebaPreTokenizer(__A ) )
def __A ( self: str , __A: str , __A: str=None ) -> int:
_A = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def __A ( self: Tuple , __A: List[int] , __A: Optional[List[int]] = None ) -> List[int]:
_A = [self.sep_token_id]
_A = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __A ( self: List[Any] , __A: str , __A: Optional[str] = None ) -> Tuple[str]:
_A = self._tokenizer.model.save(__A , name=__A )
return tuple(__A )
def __A ( self: List[str] , __A: int , __A: List[Any]=None , __A: Union[str, Any]=None , __A: List[str]=False , **__A: Optional[Any] , ) -> Dict:
_A = BertPreTokenizer()
return super().save_pretrained(__A , __A , __A , __A , **__A )
| 706 |
import logging
import os
import quant_trainer
import torch
from torch.utils.data import DataLoader
from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput
__A = logging.getLogger(__name__)
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: int , *__A: str , __A: List[Any]=None , __A: Union[str, Any]=None , __A: List[Any]=None , **__A: int ) -> List[Any]:
super().__init__(*__A , **__A )
_A = eval_examples
_A = post_process_function
_A = quant_trainer_args
_A = 1_28 # default number of calibration samples
def __A ( self: Union[str, Any] , __A: List[Any]=None ) -> Optional[Any]:
if calib_dataset is None and self.calib_dataset is None:
raise ValueError('''Trainer: calibration requires an calib_dataset.''' )
_A = calib_dataset if calib_dataset is not None else self.calib_dataset
_A = self._remove_unused_columns(__A , description='''Calibration''' )
return DataLoader(
__A , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__A , )
def __A ( self: List[Any] , __A: Any=None ) -> Optional[int]:
_A = self.train_dataset if calib_dataset is None else calib_dataset
_A = self.get_calib_dataloader(__A )
_A = self.model
quant_trainer.configure_model(__A , self.quant_trainer_args , calib=__A )
model.eval()
quant_trainer.enable_calibration(__A )
logger.info('''***** Running calibration *****''' )
logger.info(f""" Num examples = {self.calib_num}""" )
logger.info(f""" Batch size = {calib_dataloader.batch_size}""" )
for step, inputs in enumerate(__A ):
# Prediction step
_A ,_A ,_A = self.prediction_step(__A , __A , prediction_loss_only=__A )
if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
break
quant_trainer.finish_calibration(__A , self.quant_trainer_args )
_A = model
def __A ( self: Any , __A: Dict=None , __A: Tuple=None , __A: List[Any]=None , __A: str = "eval" ) -> int:
_A = self.eval_dataset if eval_dataset is None else eval_dataset
_A = self.get_eval_dataloader(__A )
_A = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is not None and self.compute_metrics is not None:
_A = self.post_process_function(__A , __A , output.predictions )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
self.log(__A )
else:
_A = {}
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
_A = self.callback_handler.on_evaluate(self.args , self.state , self.control , __A )
return metrics
def __A ( self: Union[str, Any] , __A: Optional[int] , __A: int , __A: List[Any]=None , __A: str = "test" ) -> Union[str, Any]:
_A = self.get_test_dataloader(__A )
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is None or self.compute_metrics is None:
return output
_A = self.post_process_function(__A , __A , output.predictions , '''predict''' )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__A )
def __A ( self: Tuple , __A: Optional[Any]="./" ) -> List[str]:
_A = self.eval_dataset
_A = self.get_eval_dataloader(__A )
_A = next(iter(__A ) )
# saving device - to make it consistent
_A = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' )
# convert to tuple
_A = tuple(v.to(__A ) for k, v in batch.items() )
logger.info('''Converting model to be onnx compatible''' )
from pytorch_quantization.nn import TensorQuantizer
_A = True
_A = self.model.to(__A )
model.eval()
model.float()
_A = model.module if hasattr(__A , '''module''' ) else model
quant_trainer.configure_model(__A , self.quant_trainer_args )
_A = os.path.join(__A , '''model.onnx''' )
logger.info(f"""exporting model to {output_model_file}""" )
_A = {0: '''batch_size''', 1: '''seq_len'''}
torch.onnx.export(
__A , __A , __A , export_params=__A , opset_version=13 , do_constant_folding=__A , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={
'''input_ids''': axes,
'''attention_mask''': axes,
'''token_type_ids''': axes,
'''output_start_logits''': axes,
'''output_end_logits''': axes,
} , verbose=__A , )
logger.info('''onnx export finished''' )
| 62 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "open-llama"
def __init__( self: int , __A: Optional[Any]=10_00_00 , __A: Union[str, Any]=40_96 , __A: List[str]=1_10_08 , __A: Union[str, Any]=32 , __A: Any=32 , __A: str="silu" , __A: str=20_48 , __A: Any=0.02 , __A: Optional[Any]=1e-6 , __A: str=True , __A: Optional[Any]=0 , __A: List[Any]=1 , __A: int=2 , __A: str=False , __A: List[str]=True , __A: List[str]=0.1 , __A: str=0.1 , __A: str=True , __A: List[str]=True , __A: List[str]=None , **__A: List[str] , ) -> str:
_A = vocab_size
_A = max_position_embeddings
_A = hidden_size
_A = intermediate_size
_A = num_hidden_layers
_A = num_attention_heads
_A = hidden_act
_A = initializer_range
_A = rms_norm_eps
_A = use_cache
_A = kwargs.pop(
'''use_memorry_efficient_attention''' , __A )
_A = hidden_dropout_prob
_A = attention_dropout_prob
_A = use_stable_embedding
_A = shared_input_output_embedding
_A = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , tie_word_embeddings=__A , **__A , )
def __A ( self: List[Any] ) -> Optional[Any]:
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , __A ) or len(self.rope_scaling ) != 2:
raise ValueError(
'''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
f"""got {self.rope_scaling}""" )
_A = self.rope_scaling.get('''type''' , __A )
_A = self.rope_scaling.get('''factor''' , __A )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" )
if rope_scaling_factor is None or not isinstance(__A , __A ) or rope_scaling_factor <= 1.0:
raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
| 707 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__A = {
'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MegaForCausalLM',
'MegaForMaskedLM',
'MegaForMultipleChoice',
'MegaForQuestionAnswering',
'MegaForSequenceClassification',
'MegaForTokenClassification',
'MegaModel',
'MegaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 62 | 0 |
__A = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
__A = [{'type': 'code', 'content': INSTALL_CONTENT}]
__A = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 708 |
import itertools
import string
from collections.abc import Generator, Iterable
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = iter(_lowercase )
while True:
_A = tuple(itertools.islice(_lowercase , _lowercase ) )
if not chunk:
return
yield chunk
def __A ( _lowercase ):
'''simple docstring'''
_A = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] )
_A = ''''''
if len(_lowercase ) < 2:
return dirty
for i in range(len(_lowercase ) - 1 ):
clean += dirty[i]
if dirty[i] == dirty[i + 1]:
clean += "X"
clean += dirty[-1]
if len(_lowercase ) & 1:
clean += "X"
return clean
def __A ( _lowercase ):
'''simple docstring'''
_A = '''ABCDEFGHIKLMNOPQRSTUVWXYZ'''
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
_A = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(_lowercase )
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(_lowercase )
return table
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = prepare_input(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
ciphertext += table[rowa * 5 + (cola + 1) % 5]
ciphertext += table[rowa * 5 + (cola + 1) % 5]
elif cola == cola:
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
else: # rectangle
ciphertext += table[rowa * 5 + cola]
ciphertext += table[rowa * 5 + cola]
return ciphertext
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
plaintext += table[rowa * 5 + (cola - 1) % 5]
plaintext += table[rowa * 5 + (cola - 1) % 5]
elif cola == cola:
plaintext += table[((rowa - 1) % 5) * 5 + cola]
plaintext += table[((rowa - 1) % 5) * 5 + cola]
else: # rectangle
plaintext += table[rowa * 5 + cola]
plaintext += table[rowa * 5 + cola]
return plaintext
| 62 | 0 |
from math import sqrt
def __A ( _lowercase : Optional[int] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (
number >= 0
), "'number' must been an int and positive"
_A = True
# 0 and 1 are none primes.
if number <= 1:
_A = False
for divisor in range(2 , int(round(sqrt(_lowercase ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
_A = False
break
# precondition
assert isinstance(_lowercase , _lowercase ), "'status' must been from type bool"
return status
def __A ( _lowercase : int ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
_A = list(range(2 , n + 1 ) )
_A = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(_lowercase ) ):
for j in range(i + 1 , len(_lowercase ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
_A = 0
# filters actual prime numbers.
_A = [x for x in begin_list if x != 0]
# precondition
assert isinstance(_lowercase , _lowercase ), "'ans' must been from type list"
return ans
def __A ( _lowercase : List[str] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (n > 2), "'N' must been an int and > 2"
_A = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2 , n + 1 ):
if is_prime(_lowercase ):
ans.append(_lowercase )
# precondition
assert isinstance(_lowercase , _lowercase ), "'ans' must been from type list"
return ans
def __A ( _lowercase : Union[str, Any] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and number >= 0, "'number' must been an int and >= 0"
_A = [] # this list will be returns of the function.
# potential prime number factors.
_A = 2
_A = number
if number == 0 or number == 1:
ans.append(_lowercase )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(_lowercase ):
while quotient != 1:
if is_prime(_lowercase ) and (quotient % factor == 0):
ans.append(_lowercase )
quotient /= factor
else:
factor += 1
else:
ans.append(_lowercase )
# precondition
assert isinstance(_lowercase , _lowercase ), "'ans' must been from type list"
return ans
def __A ( _lowercase : Optional[Any] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (
number >= 0
), "'number' bust been an int and >= 0"
_A = 0
# prime factorization of 'number'
_A = prime_factorization(_lowercase )
_A = max(_lowercase )
# precondition
assert isinstance(_lowercase , _lowercase ), "'ans' must been from type int"
return ans
def __A ( _lowercase : str ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (
number >= 0
), "'number' bust been an int and >= 0"
_A = 0
# prime factorization of 'number'
_A = prime_factorization(_lowercase )
_A = min(_lowercase )
# precondition
assert isinstance(_lowercase , _lowercase ), "'ans' must been from type int"
return ans
def __A ( _lowercase : Union[str, Any] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ), "'number' must been an int"
assert isinstance(number % 2 == 0 , _lowercase ), "compare bust been from type bool"
return number % 2 == 0
def __A ( _lowercase : Dict ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ), "'number' must been an int"
assert isinstance(number % 2 != 0 , _lowercase ), "compare bust been from type bool"
return number % 2 != 0
def __A ( _lowercase : Tuple ):
'''simple docstring'''
assert (
isinstance(_lowercase , _lowercase ) and (number > 2) and is_even(_lowercase )
), "'number' must been an int, even and > 2"
_A = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
_A = get_prime_numbers(_lowercase )
_A = len(_lowercase )
# run variable for while-loops.
_A = 0
_A = None
# exit variable. for break up the loops
_A = True
while i < len_pn and loop:
_A = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
_A = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(_lowercase , _lowercase )
and (len(_lowercase ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def __A ( _lowercase : Dict , _lowercase : Dict ):
'''simple docstring'''
assert (
isinstance(_lowercase , _lowercase )
and isinstance(_lowercase , _lowercase )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
_A = 0
while numbera != 0:
_A = numbera % numbera
_A = numbera
_A = rest
# precondition
assert isinstance(_lowercase , _lowercase ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def __A ( _lowercase : Tuple , _lowercase : Dict ):
'''simple docstring'''
assert (
isinstance(_lowercase , _lowercase )
and isinstance(_lowercase , _lowercase )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
_A = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
_A = prime_factorization(_lowercase )
_A = prime_factorization(_lowercase )
elif numbera == 1 or numbera == 1:
_A = []
_A = []
_A = max(_lowercase , _lowercase )
_A = 0
_A = 0
_A = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
_A = prime_fac_a.count(_lowercase )
_A = prime_fac_a.count(_lowercase )
for _ in range(max(_lowercase , _lowercase ) ):
ans *= n
else:
_A = prime_fac_a.count(_lowercase )
for _ in range(_lowercase ):
ans *= n
done.append(_lowercase )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
_A = prime_fac_a.count(_lowercase )
for _ in range(_lowercase ):
ans *= n
done.append(_lowercase )
# precondition
assert isinstance(_lowercase , _lowercase ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def __A ( _lowercase : Optional[int] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (n >= 0), "'number' must been a positive int"
_A = 0
_A = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(_lowercase ):
ans += 1
# precondition
assert isinstance(_lowercase , _lowercase ) and is_prime(
_lowercase ), "'ans' must been a prime number and from type int"
return ans
def __A ( _lowercase : Union[str, Any] , _lowercase : Union[str, Any] ):
'''simple docstring'''
assert (
is_prime(_lowercase ) and is_prime(_lowercase ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
_A = p_number_a + 1 # jump to the next number
_A = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(_lowercase ):
number += 1
while number < p_number_a:
ans.append(_lowercase )
number += 1
# fetch the next prime number.
while not is_prime(_lowercase ):
number += 1
# precondition
assert (
isinstance(_lowercase , _lowercase )
and ans[0] != p_number_a
and ans[len(_lowercase ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def __A ( _lowercase : int ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (n >= 1), "'n' must been int and >= 1"
_A = [] # will be returned.
for divisor in range(1 , n + 1 ):
if n % divisor == 0:
ans.append(_lowercase )
# precondition
assert ans[0] == 1 and ans[len(_lowercase ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def __A ( _lowercase : List[Any] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (
number > 1
), "'number' must been an int and >= 1"
_A = get_divisors(_lowercase )
# precondition
assert (
isinstance(_lowercase , _lowercase )
and (divisors[0] == 1)
and (divisors[len(_lowercase ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def __A ( _lowercase : Any , _lowercase : Union[str, Any] ):
'''simple docstring'''
assert (
isinstance(_lowercase , _lowercase )
and isinstance(_lowercase , _lowercase )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
_A = gcd(abs(_lowercase ) , abs(_lowercase ) )
# precondition
assert (
isinstance(_lowercase , _lowercase )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def __A ( _lowercase : Optional[Any] ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (n >= 0), "'n' must been a int and >= 0"
_A = 1 # this will be return.
for factor in range(1 , n + 1 ):
ans *= factor
return ans
def __A ( _lowercase : Tuple ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase ) and (n >= 0), "'n' must been an int and >= 0"
_A = 0
_A = 1
_A = 1 # this will be return
for _ in range(n - 1 ):
_A = ans
ans += fiba
_A = tmp
return ans
| 709 |
import gc
import unittest
from transformers import CTRLConfig, 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, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Tuple , __A: Any , __A: List[Any]=14 , __A: Dict=7 , __A: List[str]=True , __A: Tuple=True , __A: Union[str, Any]=True , __A: List[Any]=True , __A: Optional[int]=True , __A: Tuple=99 , __A: Optional[Any]=32 , __A: List[str]=5 , __A: Dict=4 , __A: str=37 , __A: Dict="gelu" , __A: List[str]=0.1 , __A: str=0.1 , __A: Any=5_12 , __A: Union[str, Any]=16 , __A: List[Any]=2 , __A: Tuple=0.02 , __A: Tuple=3 , __A: Union[str, Any]=4 , __A: Any=None , ) -> Optional[Any]:
_A = parent
_A = batch_size
_A = seq_length
_A = is_training
_A = use_token_type_ids
_A = use_input_mask
_A = use_labels
_A = use_mc_token_ids
_A = vocab_size
_A = hidden_size
_A = num_hidden_layers
_A = num_attention_heads
_A = intermediate_size
_A = hidden_act
_A = hidden_dropout_prob
_A = attention_probs_dropout_prob
_A = max_position_embeddings
_A = type_vocab_size
_A = type_sequence_label_size
_A = initializer_range
_A = num_labels
_A = num_choices
_A = scope
_A = self.vocab_size - 1
def __A ( self: Optional[int] ) -> Union[str, Any]:
_A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_A = None
if self.use_input_mask:
_A = random_attention_mask([self.batch_size, self.seq_length] )
_A = None
if self.use_token_type_ids:
_A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_A = None
if self.use_mc_token_ids:
_A = ids_tensor([self.batch_size, self.num_choices] , self.seq_length )
_A = None
_A = None
_A = None
if self.use_labels:
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_A = ids_tensor([self.batch_size] , self.num_choices )
_A = self.get_config()
_A = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
token_type_ids,
mc_token_ids,
sequence_labels,
token_labels,
choice_labels,
)
def __A ( self: Optional[int] ) -> List[Any]:
return CTRLConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , )
def __A ( self: Union[str, Any] , __A: Union[str, Any] , __A: Dict , __A: Optional[int] , __A: List[str] , __A: List[str] , *__A: Optional[int] ) -> Optional[Any]:
_A = CTRLModel(config=__A )
model.to(__A )
model.eval()
model(__A , token_type_ids=__A , head_mask=__A )
model(__A , token_type_ids=__A )
_A = model(__A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(len(result.past_key_values ) , config.n_layer )
def __A ( self: Optional[Any] , __A: List[str] , __A: Dict , __A: List[Any] , __A: List[Any] , __A: Any , *__A: Any ) -> str:
_A = CTRLLMHeadModel(__A )
model.to(__A )
model.eval()
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __A ( self: Optional[int] ) -> Dict:
_A = self.prepare_config_and_inputs()
(
(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,
) = config_and_inputs
_A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}
return config, inputs_dict
def __A ( self: List[str] , __A: Dict , __A: Dict , __A: Tuple , __A: List[Any] , *__A: Optional[int] ) -> Any:
_A = self.num_labels
_A = CTRLForSequenceClassification(__A )
model.to(__A )
model.eval()
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
A_ = (CTRLLMHeadModel,) if is_torch_available() else ()
A_ = (
{
"feature-extraction": CTRLModel,
"text-classification": CTRLForSequenceClassification,
"text-generation": CTRLLMHeadModel,
"zero-shot": CTRLForSequenceClassification,
}
if is_torch_available()
else {}
)
A_ = True
A_ = False
A_ = False
def __A ( self: Any , __A: List[Any] , __A: int , __A: Optional[Any] , __A: Optional[int] , __A: List[Any] ) -> List[str]:
if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
# config could not be created.
return True
return False
def __A ( self: Any ) -> Union[str, Any]:
_A = CTRLModelTester(self )
_A = ConfigTester(self , config_class=__A , n_embd=37 )
def __A ( self: Optional[int] ) -> List[Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
def __A ( self: Dict ) -> Any:
self.config_tester.run_common_tests()
def __A ( self: str ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_ctrl_model(*__A )
def __A ( self: List[str] ) -> Any:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head_model(*__A )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: Optional[Any] ) -> int:
pass
@slow
def __A ( self: Tuple ) -> Dict:
for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_A = CTRLModel.from_pretrained(__A )
self.assertIsNotNone(__A )
@unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :)
def __A ( self: Any ) -> Union[str, Any]:
pass
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: int ) -> Union[str, Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
@slow
def __A ( self: Any ) -> Any:
_A = CTRLLMHeadModel.from_pretrained('''ctrl''' )
model.to(__A )
_A = torch.tensor(
[[1_18_59, 0, 16_11, 8]] , dtype=torch.long , device=__A ) # Legal the president is
_A = [
1_18_59,
0,
16_11,
8,
5,
1_50,
2_64_49,
2,
19,
3_48,
4_69,
3,
25_95,
48,
2_07_40,
24_65_33,
24_65_33,
19,
30,
5,
] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a
_A = model.generate(__A , do_sample=__A )
self.assertListEqual(output_ids[0].tolist() , __A )
| 62 | 0 |
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__A = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , torch.Tensor ):
return image
elif isinstance(_lowercase , PIL.Image.Image ):
_A = [image]
_A = [trans(img.convert('''RGB''' ) ) for img in image]
_A = torch.stack(_lowercase )
return image
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: Dict , __A: Optional[int] , __A: int ) -> Optional[Any]:
super().__init__()
# make sure scheduler can always be converted to DDIM
_A = DDIMScheduler.from_config(scheduler.config )
self.register_modules(unet=__A , scheduler=__A )
def __A ( self: List[Any] , __A: Dict ) -> str:
if strength < 0 or strength > 1:
raise ValueError(f"""The value of strength should in [0.0, 1.0] but is {strength}""" )
def __A ( self: Tuple , __A: str , __A: Tuple , __A: Tuple ) -> str:
# get the original timestep using init_timestep
_A = min(int(num_inference_steps * strength ) , __A )
_A = max(num_inference_steps - init_timestep , 0 )
_A = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def __A ( self: Union[str, Any] , __A: Optional[int] , __A: List[str] , __A: List[str] , __A: Dict , __A: str , __A: Tuple=None ) -> List[Any]:
if not isinstance(__A , (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(__A )}""" )
_A = image.to(device=__A , dtype=__A )
if isinstance(__A , __A ) and len(__A ) != batch_size:
raise ValueError(
f"""You have passed a list of generators of length {len(__A )}, but requested an effective batch"""
f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
_A = init_latents.shape
_A = randn_tensor(__A , generator=__A , device=__A , dtype=__A )
# get latents
print('''add noise to latents at timestep''' , __A )
_A = self.scheduler.add_noise(__A , __A , __A )
_A = init_latents
return latents
@torch.no_grad()
def __call__( self: Dict , __A: Union[torch.FloatTensor, PIL.Image.Image] = None , __A: float = 0.8 , __A: int = 1 , __A: Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A: float = 0.0 , __A: int = 50 , __A: Optional[bool] = None , __A: Optional[str] = "pil" , __A: bool = True , ) -> Union[ImagePipelineOutput, Tuple]:
self.check_inputs(__A )
# 2. Preprocess image
_A = preprocess(__A )
# 3. set timesteps
self.scheduler.set_timesteps(__A , device=self.device )
_A ,_A = self.get_timesteps(__A , __A , self.device )
_A = timesteps[:1].repeat(__A )
# 4. Prepare latent variables
_A = self.prepare_latents(__A , __A , __A , self.unet.dtype , self.device , __A )
_A = latents
# 5. Denoising loop
for t in self.progress_bar(__A ):
# 1. predict noise model_output
_A = self.unet(__A , __A ).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta
# eta corresponds to η in paper and should be between [0, 1]
# do x_t -> x_t-1
_A = self.scheduler.step(
__A , __A , __A , eta=__A , use_clipped_model_output=__A , generator=__A , ).prev_sample
_A = (image / 2 + 0.5).clamp(0 , 1 )
_A = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
_A = self.numpy_to_pil(__A )
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=__A )
| 710 |
__A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
__A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = []
for neighbour in graph[vert]:
if not visited[neighbour]:
order += topology_sort(_lowercase , _lowercase , _lowercase )
order.append(_lowercase )
return order
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = [vert]
for neighbour in reversed_graph[vert]:
if not visited[neighbour]:
component += find_components(_lowercase , _lowercase , _lowercase )
return component
def __A ( _lowercase ):
'''simple docstring'''
_A = len(_lowercase ) * [False]
_A = {vert: [] for vert in range(len(_lowercase ) )}
for vert, neighbours in graph.items():
for neighbour in neighbours:
reversed_graph[neighbour].append(_lowercase )
_A = []
for i, was_visited in enumerate(_lowercase ):
if not was_visited:
order += topology_sort(_lowercase , _lowercase , _lowercase )
_A = []
_A = len(_lowercase ) * [False]
for i in range(len(_lowercase ) ):
_A = order[len(_lowercase ) - i - 1]
if not visited[vert]:
_A = find_components(_lowercase , _lowercase , _lowercase )
components_list.append(_lowercase )
return components_list
| 62 | 0 |
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from transformers import (
VisualBertConfig,
VisualBertForMultipleChoice,
VisualBertForPreTraining,
VisualBertForQuestionAnswering,
VisualBertForVisualReasoning,
)
from transformers.utils import logging
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
__A = [
('bert.bert', 'visual_bert'),
('bert.cls', 'cls'),
('bert.classifier', 'cls'),
('token_type_embeddings_visual', 'visual_token_type_embeddings'),
('position_embeddings_visual', 'visual_position_embeddings'),
('projection', 'visual_projection'),
]
__A = [
'nlvr2_coco_pre_trained.th',
'nlvr2_fine_tuned.th',
'nlvr2_pre_trained.th',
'vcr_coco_pre_train.th',
'vcr_fine_tune.th',
'vcr_pre_train.th',
'vqa_coco_pre_trained.th',
'vqa_fine_tuned.th',
'vqa_pre_trained.th',
]
def __A ( _lowercase ):
'''simple docstring'''
_A = torch.load(_lowercase , map_location='''cpu''' )
return sd
def __A ( _lowercase , _lowercase , _lowercase=rename_keys_prefix ):
'''simple docstring'''
_A = OrderedDict()
_A = torch.arange(config.max_position_embeddings ).expand((1, -1) )
# detector_d = OrderedDict()
for key in d:
if "detector" in key:
# detector_d[key.replace('detector.','')] = d[key]
continue
_A = key
for name_pair in rename_keys_prefix:
_A = new_key.replace(name_pair[0] , name_pair[1] )
_A = d[key]
if key == "bert.cls.predictions.decoder.weight":
# Old bert code didn't have `decoder.bias`, but was added separately
_A = new_d['''cls.predictions.bias''']
return new_d
@torch.no_grad()
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
assert (
checkpoint_path.split('''/''' )[-1] in ACCEPTABLE_CHECKPOINTS
), f"""The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}."""
# Get Config
if "pre" in checkpoint_path:
_A = '''pretraining'''
if "vcr" in checkpoint_path:
_A = {'''visual_embedding_dim''': 5_12}
elif "vqa_advanced" in checkpoint_path:
_A = {'''visual_embedding_dim''': 20_48}
elif "vqa" in checkpoint_path:
_A = {'''visual_embedding_dim''': 20_48}
elif "nlvr" in checkpoint_path:
_A = {'''visual_embedding_dim''': 10_24}
else:
raise NotImplementedError(f"""No implementation found for `{checkpoint_path}`.""" )
else:
if "vcr" in checkpoint_path:
_A = {'''visual_embedding_dim''': 5_12}
_A = '''multichoice'''
elif "vqa_advanced" in checkpoint_path:
_A = {'''visual_embedding_dim''': 20_48}
_A = '''vqa_advanced'''
elif "vqa" in checkpoint_path:
_A = {'''visual_embedding_dim''': 20_48, '''num_labels''': 31_29}
_A = '''vqa'''
elif "nlvr" in checkpoint_path:
_A = {
'''visual_embedding_dim''': 10_24,
'''num_labels''': 2,
}
_A = '''nlvr'''
_A = VisualBertConfig(**_lowercase )
# Load State Dict
_A = load_state_dict(_lowercase )
_A = get_new_dict(_lowercase , _lowercase )
if model_type == "pretraining":
_A = VisualBertForPreTraining(_lowercase )
elif model_type == "vqa":
_A = VisualBertForQuestionAnswering(_lowercase )
elif model_type == "nlvr":
_A = VisualBertForVisualReasoning(_lowercase )
elif model_type == "multichoice":
_A = VisualBertForMultipleChoice(_lowercase )
model.load_state_dict(_lowercase )
# Save Checkpoints
Path(_lowercase ).mkdir(exist_ok=_lowercase )
model.save_pretrained(_lowercase )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument('orig_checkpoint_path', type=str, help='A path to .th on local filesystem.')
parser.add_argument('pytorch_dump_folder_path', type=str, help='Path to the output PyTorch model.')
__A = parser.parse_args()
convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
| 711 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
global f # a global dp table for knapsack
if f[i][j] < 0:
if j < wt[i - 1]:
_A = mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase )
else:
_A = max(
mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase ) , mf_knapsack(i - 1 , _lowercase , _lowercase , j - wt[i - 1] ) + val[i - 1] , )
_A = val
return f[i][j]
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = [[0] * (w + 1) for _ in range(n + 1 )]
for i in range(1 , n + 1 ):
for w_ in range(1 , w + 1 ):
if wt[i - 1] <= w_:
_A = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] )
else:
_A = dp[i - 1][w_]
return dp[n][w_], dp
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if not (isinstance(_lowercase , (list, tuple) ) and isinstance(_lowercase , (list, tuple) )):
raise ValueError(
'''Both the weights and values vectors must be either lists or tuples''' )
_A = len(_lowercase )
if num_items != len(_lowercase ):
_A = (
'''The number of weights must be the same as the number of values.\n'''
f"""But got {num_items} weights and {len(_lowercase )} values"""
)
raise ValueError(_lowercase )
for i in range(_lowercase ):
if not isinstance(wt[i] , _lowercase ):
_A = (
'''All weights must be integers but got weight of '''
f"""type {type(wt[i] )} at index {i}"""
)
raise TypeError(_lowercase )
_A ,_A = knapsack(_lowercase , _lowercase , _lowercase , _lowercase )
_A = set()
_construct_solution(_lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
return optimal_val, example_optional_set
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if i > 0 and j > 0:
if dp[i - 1][j] == dp[i][j]:
_construct_solution(_lowercase , _lowercase , i - 1 , _lowercase , _lowercase )
else:
optimal_set.add(_lowercase )
_construct_solution(_lowercase , _lowercase , i - 1 , j - wt[i - 1] , _lowercase )
if __name__ == "__main__":
__A = [3, 2, 4, 4]
__A = [4, 3, 2, 3]
__A = 4
__A = 6
__A = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)]
__A , __A = knapsack(w, wt, val, n)
print(optimal_solution)
print(mf_knapsack(n, wt, val, w)) # switched the n and w
# testing the dynamic programming problem with example
# the optimal subset for the above example are items 3 and 4
__A , __A = knapsack_with_example_solution(w, wt, val)
assert optimal_solution == 8
assert optimal_subset == {3, 4}
print('optimal_value = ', optimal_solution)
print('An optimal subset corresponding to the optimal value', optimal_subset)
| 62 | 0 |
from typing import List, Optional, Union
import torch
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,
)
__A = logging.get_logger(__name__) # pylint: disable=invalid-name
__A = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n'
def __A ( _lowercase , _lowercase , _lowercase=8 ):
'''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
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: List[Any] , __A: UNetaDConditionModel , __A: DDPMScheduler , __A: VQModel , ) -> List[Any]:
super().__init__()
self.register_modules(
unet=__A , scheduler=__A , movq=__A , )
_A = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def __A ( self: Union[str, Any] , __A: Optional[Any] , __A: int , __A: int , __A: Tuple , __A: List[str] , __A: Optional[int] ) -> Union[str, Any]:
if latents is None:
_A = randn_tensor(__A , generator=__A , device=__A , dtype=__A )
else:
if latents.shape != shape:
raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" )
_A = latents.to(__A )
_A = latents * scheduler.init_noise_sigma
return latents
def __A ( self: Optional[Any] , __A: Any=0 ) -> Dict:
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(__A , __A )
def __A ( self: List[Any] , __A: Union[str, Any]=0 ) -> List[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=__A )
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 ,_A = cpu_offload_with_hook(__A , __A , prev_module_hook=__A )
# We'll offload the last model manually.
_A = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def __A ( self: Union[str, Any] ) -> List[str]:
if not hasattr(self.unet , '''_hf_hook''' ):
return self.device
for module in self.unet.modules():
if (
hasattr(__A , '''_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(__A )
def __call__( self: Union[str, Any] , __A: Union[torch.FloatTensor, List[torch.FloatTensor]] , __A: Union[torch.FloatTensor, List[torch.FloatTensor]] , __A: int = 5_12 , __A: int = 5_12 , __A: int = 1_00 , __A: float = 4.0 , __A: int = 1 , __A: Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A: Optional[torch.FloatTensor] = None , __A: Optional[str] = "pil" , __A: bool = True , ) -> Any:
_A = self._execution_device
_A = guidance_scale > 1.0
if isinstance(__A , __A ):
_A = torch.cat(__A , dim=0 )
_A = image_embeds.shape[0] * num_images_per_prompt
if isinstance(__A , __A ):
_A = torch.cat(__A , dim=0 )
if do_classifier_free_guidance:
_A = image_embeds.repeat_interleave(__A , dim=0 )
_A = negative_image_embeds.repeat_interleave(__A , dim=0 )
_A = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__A )
self.scheduler.set_timesteps(__A , device=__A )
_A = self.scheduler.timesteps
_A = self.unet.config.in_channels
_A ,_A = downscale_height_and_width(__A , __A , self.movq_scale_factor )
# create initial latent
_A = self.prepare_latents(
(batch_size, num_channels_latents, height, width) , image_embeds.dtype , __A , __A , __A , self.scheduler , )
for i, t in enumerate(self.progress_bar(__A ) ):
# 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=__A , timestep=__A , encoder_hidden_states=__A , added_cond_kwargs=__A , return_dict=__A , )[0]
if do_classifier_free_guidance:
_A ,_A = noise_pred.split(latents.shape[1] , dim=1 )
_A ,_A = noise_pred.chunk(2 )
_A ,_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 ,_A = noise_pred.split(latents.shape[1] , dim=1 )
# compute the previous noisy sample x_t -> x_t-1
_A = self.scheduler.step(
__A , __A , __A , generator=__A , )[0]
# post-processing
_A = self.movq.decode(__A , force_not_quantize=__A )['''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(__A )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=__A )
| 712 |
def __A ( _lowercase = 1_00_00_00 ):
'''simple docstring'''
_A = 1
_A = 1
_A = {1: 1}
for inputa in range(2 , _lowercase ):
_A = 0
_A = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_A = (3 * number) + 1
counter += 1
if inputa not in counters:
_A = counter
if counter > pre_counter:
_A = inputa
_A = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__A = {
'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'],
'tokenization_biogpt': ['BioGptTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST',
'BioGptForCausalLM',
'BioGptForTokenClassification',
'BioGptForSequenceClassification',
'BioGptModel',
'BioGptPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
from .tokenization_biogpt import BioGptTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_biogpt import (
BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
BioGptForCausalLM,
BioGptForSequenceClassification,
BioGptForTokenClassification,
BioGptModel,
BioGptPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 713 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = word.split()
def justify(_lowercase , _lowercase , _lowercase ) -> str:
_A = max_width - width
_A = len(_lowercase )
if len(_lowercase ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_A = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_A = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_A = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_lowercase ):
num_spaces_between_words_list[i] += 1
_A = []
for i in range(_lowercase ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * ''' ''' )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_lowercase )
_A = []
_A = []
_A = 0
for word in words:
if width + len(_lowercase ) + len(_lowercase ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_lowercase )
width += len(_lowercase )
else:
# justify the line and add it to result
answer.append(justify(_lowercase , _lowercase , _lowercase ) )
# reset new line and new width
_A ,_A = [word], len(_lowercase )
_A = max_width - width - len(_lowercase )
answer.append(''' '''.join(_lowercase ) + (remaining_spaces + 1) * ''' ''' )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 62 | 0 |
import copy
import json
import os
import tempfile
from transformers import is_torch_available
from .test_configuration_utils import config_common_kwargs
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: Dict , __A: Dict , __A: List[str]=None , __A: Optional[Any]=True , __A: str=None , **__A: List[str] ) -> Any:
_A = parent
_A = config_class
_A = has_text_modality
_A = kwargs
_A = common_properties
def __A ( self: int ) -> Optional[int]:
_A = self.config_class(**self.inputs_dict )
_A = (
['''hidden_size''', '''num_attention_heads''', '''num_hidden_layers''']
if self.common_properties is None
else self.common_properties
)
# Add common fields for text models
if self.has_text_modality:
common_properties.extend(['''vocab_size'''] )
# Test that config has the common properties as getters
for prop in common_properties:
self.parent.assertTrue(hasattr(__A , __A ) , msg=f"""`{prop}` does not exist""" )
# Test that config has the common properties as setter
for idx, name in enumerate(__A ):
try:
setattr(__A , __A , __A )
self.parent.assertEqual(
getattr(__A , __A ) , __A , msg=f"""`{name} value {idx} expected, but was {getattr(__A , __A )}""" )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
# Test if config class can be called with Config(prop_name=..)
for idx, name in enumerate(__A ):
try:
_A = self.config_class(**{name: idx} )
self.parent.assertEqual(
getattr(__A , __A ) , __A , msg=f"""`{name} value {idx} expected, but was {getattr(__A , __A )}""" )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
def __A ( self: Tuple ) -> List[str]:
_A = self.config_class(**self.inputs_dict )
_A = json.loads(config.to_json_string() )
for key, value in self.inputs_dict.items():
self.parent.assertEqual(obj[key] , __A )
def __A ( self: Union[str, Any] ) -> Optional[int]:
_A = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
_A = os.path.join(__A , '''config.json''' )
config_first.to_json_file(__A )
_A = self.config_class.from_json_file(__A )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def __A ( self: str ) -> Optional[Any]:
_A = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
config_first.save_pretrained(__A )
_A = self.config_class.from_pretrained(__A )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def __A ( self: Optional[Any] ) -> Dict:
_A = self.config_class(**self.inputs_dict )
_A = '''test'''
with tempfile.TemporaryDirectory() as tmpdirname:
_A = os.path.join(__A , __A )
config_first.save_pretrained(__A )
_A = self.config_class.from_pretrained(__A , subfolder=__A )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def __A ( self: int ) -> Tuple:
_A = self.config_class(**self.inputs_dict , num_labels=5 )
self.parent.assertEqual(len(config.idalabel ) , 5 )
self.parent.assertEqual(len(config.labelaid ) , 5 )
_A = 3
self.parent.assertEqual(len(config.idalabel ) , 3 )
self.parent.assertEqual(len(config.labelaid ) , 3 )
def __A ( self: List[str] ) -> List[Any]:
if self.config_class.is_composition:
return
_A = self.config_class()
self.parent.assertIsNotNone(__A )
def __A ( self: Dict ) -> Dict:
_A = copy.deepcopy(__A )
_A = self.config_class(**__A )
_A = []
for key, value in config_common_kwargs.items():
if key == "torch_dtype":
if not is_torch_available():
continue
else:
import torch
if config.torch_dtype != torch.floataa:
wrong_values.append(('''torch_dtype''', config.torch_dtype, torch.floataa) )
elif getattr(__A , __A ) != value:
wrong_values.append((key, getattr(__A , __A ), value) )
if len(__A ) > 0:
_A = '''\n'''.join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] )
raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" )
def __A ( self: List[Any] ) -> str:
self.create_and_test_config_common_properties()
self.create_and_test_config_to_json_string()
self.create_and_test_config_to_json_file()
self.create_and_test_config_from_and_save_pretrained()
self.create_and_test_config_from_and_save_pretrained_subfolder()
self.create_and_test_config_with_num_labels()
self.check_config_can_be_init_without_params()
self.check_config_arguments_init()
| 714 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(_lowercase , '''utf-8''' )
with zstd.open(_lowercase , '''wb''' ) as f:
f.write(_lowercase )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , _lowercase ) , '''w''' ) as f:
f.write(_lowercase )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=_lowercase , extract_compressed_file=_lowercase )
_A = cached_path(_lowercase , download_config=_lowercase )
with open(_lowercase ) as f:
_A = f.read()
with open(_lowercase ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , _lowercase )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(_lowercase ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=_lowercase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowercase )
)
_A = cached_path(_lowercase , download_config=_lowercase )
assert Path(_lowercase ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(_lowercase ).resolve() )
assert cached_path(_lowercase ) == text_file
# relative path
_A = str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowercase ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(_lowercase ):
cached_path(_lowercase )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(_lowercase ):
cached_path(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(_lowercase ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( ):
'''simple docstring'''
with pytest.raises(_lowercase ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
http_get('''https://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
ftp_get('''ftp://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
fsspec_get('''s3://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
fsspec_head('''s3://huggingface.co''' )
| 62 | 0 |
'''simple docstring'''
from typing import Dict, List
from nltk.translate import gleu_score
import datasets
from datasets import MetricInfo
__A = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n'
__A = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n'
__A = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class SCREAMING_SNAKE_CASE ( datasets.Metric ):
"""simple docstring"""
def __A ( self: Union[str, Any] ) -> MetricInfo:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ),
'''references''': datasets.Sequence(
datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ),
} ) , )
def __A ( self: Optional[int] , __A: List[List[List[str]]] , __A: List[List[str]] , __A: int = 1 , __A: int = 4 , ) -> Dict[str, float]:
return {
"google_bleu": gleu_score.corpus_gleu(
list_of_references=__A , hypotheses=__A , min_len=__A , max_len=__A )
}
| 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 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2
def __A ( _lowercase , _lowercase=0 ):
'''simple docstring'''
return sorted(_lowercase , key=lambda _lowercase : x[column] )
def __A ( _lowercase , _lowercase , _lowercase=float('''inf''' ) ):
'''simple docstring'''
for i in range(points_counts - 1 ):
for j in range(i + 1 , _lowercase ):
_A = euclidean_distance_sqr(points[i] , points[j] )
if current_dis < min_dis:
_A = current_dis
return min_dis
def __A ( _lowercase , _lowercase , _lowercase=float('''inf''' ) ):
'''simple docstring'''
for i in range(min(6 , points_counts - 1 ) , _lowercase ):
for j in range(max(0 , i - 6 ) , _lowercase ):
_A = euclidean_distance_sqr(points[i] , points[j] )
if current_dis < min_dis:
_A = current_dis
return min_dis
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if points_counts <= 3:
return dis_between_closest_pair(_lowercase , _lowercase )
# recursion
_A = points_counts // 2
_A = closest_pair_of_points_sqr(
_lowercase , points_sorted_on_y[:mid] , _lowercase )
_A = closest_pair_of_points_sqr(
_lowercase , points_sorted_on_y[mid:] , points_counts - mid )
_A = min(_lowercase , _lowercase )
_A = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis:
cross_strip.append(_lowercase )
_A = dis_between_closest_in_strip(
_lowercase , len(_lowercase ) , _lowercase )
return min(_lowercase , _lowercase )
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = column_based_sort(_lowercase , column=0 )
_A = column_based_sort(_lowercase , column=1 )
return (
closest_pair_of_points_sqr(
_lowercase , _lowercase , _lowercase )
) ** 0.5
if __name__ == "__main__":
__A = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print('Distance:', closest_pair_of_points(points, len(points)))
| 716 |
import flax.linen as nn
import jax
import jax.numpy as jnp
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: Tuple ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Dict , __A: Dict ) -> Tuple:
_A ,_A ,_A ,_A = hidden_states.shape
_A = jax.image.resize(
__A , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , )
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: List[str] ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Union[str, Any] , __A: List[Any] ) -> Union[str, Any]:
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = None
A_ = 0.0
A_ = None
A_ = jnp.floataa
def __A ( self: Dict ) -> Dict:
_A = self.in_channels if self.out_channels is None else self.out_channels
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = nn.Dense(__A , dtype=self.dtype )
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Dropout(self.dropout_prob )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
_A = None
if use_nin_shortcut:
_A = nn.Conv(
__A , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , )
def __call__( self: Dict , __A: List[Any] , __A: List[Any] , __A: Any=True ) -> List[Any]:
_A = hidden_states
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.conva(__A )
_A = self.time_emb_proj(nn.swish(__A ) )
_A = jnp.expand_dims(jnp.expand_dims(__A , 1 ) , 1 )
_A = hidden_states + temb
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.dropout(__A , __A )
_A = self.conva(__A )
if self.conv_shortcut is not None:
_A = self.conv_shortcut(__A )
return hidden_states + residual
| 62 | 0 |
import logging
import os
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
from accelerate.utils.imports import (
is_abit_bnb_available,
is_abit_bnb_available,
is_bnb_available,
)
from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
find_tied_parameters,
get_balanced_memory,
infer_auto_device_map,
load_checkpoint_in_model,
offload_weight,
set_module_tensor_to_device,
)
if is_bnb_available():
import bitsandbytes as bnb
from copy import deepcopy
__A = logging.getLogger(__name__)
def __A ( _lowercase , _lowercase , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = False , ):
'''simple docstring'''
_A = bnb_quantization_config.load_in_abit
_A = bnb_quantization_config.load_in_abit
if load_in_abit and not is_abit_bnb_available():
raise ImportError(
'''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'''
''' make sure you have the latest version of `bitsandbytes` installed.''' )
if load_in_abit and not is_abit_bnb_available():
raise ValueError(
'''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'''
'''make sure you have the latest version of `bitsandbytes` installed.''' )
_A = []
# custom device map
if isinstance(_lowercase , _lowercase ) and len(device_map.keys() ) > 1:
_A = [key for key, value in device_map.items() if value in ['''disk''', '''cpu''']]
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
if bnb_quantization_config.skip_modules is None:
_A = get_keys_to_not_convert(_lowercase )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(_lowercase )
_A = bnb_quantization_config.skip_modules
# We add the modules we want to keep in full precision
if bnb_quantization_config.keep_in_fpaa_modules is None:
_A = []
_A = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(_lowercase )
# compatibility with peft
_A = load_in_abit
_A = load_in_abit
_A = get_parameter_device(_lowercase )
if model_device.type != "meta":
# quantization of an already loaded model
logger.warning(
'''It is not recommended to quantize a loaded model. '''
'''The model should be instantiated under the `init_empty_weights` context manager.''' )
_A = replace_with_bnb_layers(_lowercase , _lowercase , modules_to_not_convert=_lowercase )
# convert param to the right dtype
_A = bnb_quantization_config.torch_dtype
for name, param in model.state_dict().items():
if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ):
param.to(torch.floataa )
if param.dtype != torch.floataa:
_A = name.replace('''.weight''' , '''''' ).replace('''.bias''' , '''''' )
_A = getattr(_lowercase , _lowercase , _lowercase )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(_lowercase ):
param.to(_lowercase )
if model_device.type == "cuda":
# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
model.cuda(torch.cuda.current_device() )
torch.cuda.empty_cache()
elif torch.cuda.is_available():
model.to(torch.cuda.current_device() )
else:
raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' )
logger.info(
f"""The model device type is {model_device.type}. However, cuda is needed for quantization."""
'''We move the model to cuda.''' )
return model
elif weights_location is None:
raise RuntimeError(
f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ )
else:
with init_empty_weights():
_A = replace_with_bnb_layers(
_lowercase , _lowercase , modules_to_not_convert=_lowercase )
_A = get_quantized_model_device_map(
_lowercase , _lowercase , _lowercase , max_memory=_lowercase , no_split_module_classes=_lowercase , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
_A = True
_A = any(x in list(device_map.values() ) for x in ['''cpu''', '''disk'''] )
load_checkpoint_in_model(
_lowercase , _lowercase , _lowercase , dtype=bnb_quantization_config.torch_dtype , offload_folder=_lowercase , offload_state_dict=_lowercase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(_lowercase , device_map=_lowercase , offload_dir=_lowercase )
def __A ( _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ):
'''simple docstring'''
if device_map is None:
if torch.cuda.is_available():
_A = {'''''': torch.cuda.current_device()}
else:
raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' )
logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.''' )
if isinstance(_lowercase , _lowercase ):
if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
raise ValueError(
'''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '''
'''\'sequential\'.''' )
_A = {}
special_dtypes.update(
{
name: bnb_quantization_config.torch_dtype
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.skip_modules )
} )
special_dtypes.update(
{
name: torch.floataa
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules )
} )
_A = {}
_A = special_dtypes
_A = no_split_module_classes
_A = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
_A = get_balanced_memory(
_lowercase , low_zero=(device_map == '''balanced_low_0''') , max_memory=_lowercase , **_lowercase , )
_A = max_memory
_A = infer_auto_device_map(_lowercase , **_lowercase )
if isinstance(_lowercase , _lowercase ):
# check if don't have any quantized module on the cpu
_A = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
_A = {
key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
}
for device in ["cpu", "disk"]:
if device in device_map_without_some_modules.values():
if bnb_quantization_config.load_in_abit:
raise ValueError(
'''
Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
these modules in `torch_dtype`, you need to pass a custom `device_map` to
`load_and_quantize_model`. Check
https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
for more details.
''' )
else:
logger.info(
'''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit''' )
del device_map_without_some_modules
return device_map
def __A ( _lowercase , _lowercase , _lowercase=None , _lowercase=None ):
'''simple docstring'''
if modules_to_not_convert is None:
_A = []
_A ,_A = _replace_with_bnb_layers(
_lowercase , _lowercase , _lowercase , _lowercase )
if not has_been_replaced:
logger.warning(
'''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'''
''' Please double check your model architecture, or submit an issue on github if you think this is'''
''' a bug.''' )
return model
def __A ( _lowercase , _lowercase , _lowercase=None , _lowercase=None , ):
'''simple docstring'''
_A = False
for name, module in model.named_children():
if current_key_name is None:
_A = []
current_key_name.append(_lowercase )
if isinstance(_lowercase , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
_A = '''.'''.join(_lowercase )
_A = True
for key in modules_to_not_convert:
if (
(key in current_key_name_str) and (key + "." in current_key_name_str)
) or key == current_key_name_str:
_A = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
_A = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_lowercase , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
_A = bnb.nn.Linearabit(
module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , )
else:
raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False''' )
_A = module.weight.data
if module.bias is not None:
_A = module.bias.data
bnb_module.requires_grad_(_lowercase )
setattr(_lowercase , _lowercase , _lowercase )
_A = True
if len(list(module.children() ) ) > 0:
_A ,_A = _replace_with_bnb_layers(
_lowercase , _lowercase , _lowercase , _lowercase )
_A = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def __A ( _lowercase ):
'''simple docstring'''
with init_empty_weights():
_A = deepcopy(_lowercase ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
_A = find_tied_parameters(_lowercase )
# For compatibility with Accelerate < 0.18
if isinstance(_lowercase , _lowercase ):
_A = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
_A = sum(_lowercase , [] )
_A = len(_lowercase ) > 0
# Check if it is a base model
_A = False
if hasattr(_lowercase , '''base_model_prefix''' ):
_A = not hasattr(_lowercase , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
_A = list(model.named_children() )
_A = [list_modules[-1][0]]
# add last module together with tied weights
_A = set(_lowercase ) - set(_lowercase )
_A = list(set(_lowercase ) ) + list(_lowercase )
# remove ".weight" from the keys
_A = ['''.weight''', '''.bias''']
_A = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
_A = name.replace(_lowercase , '''''' )
filtered_module_names.append(_lowercase )
return filtered_module_names
def __A ( _lowercase ):
'''simple docstring'''
for m in model.modules():
if isinstance(_lowercase , bnb.nn.Linearabit ):
return True
return False
def __A ( _lowercase ):
'''simple docstring'''
return next(parameter.parameters() ).device
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if fpaa_statistics is None:
set_module_tensor_to_device(_lowercase , _lowercase , 0 , dtype=_lowercase , value=_lowercase )
_A = param_name
_A = model
if "." in tensor_name:
_A = tensor_name.split('''.''' )
for split in splits[:-1]:
_A = getattr(_lowercase , _lowercase )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
_A = new_module
_A = splits[-1]
# offload weights
_A = False
offload_weight(module._parameters[tensor_name] , _lowercase , _lowercase , index=_lowercase )
if hasattr(module._parameters[tensor_name] , '''SCB''' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('''weight''' , '''SCB''' ) , _lowercase , index=_lowercase , )
else:
offload_weight(_lowercase , _lowercase , _lowercase , index=_lowercase )
offload_weight(_lowercase , param_name.replace('''weight''' , '''SCB''' ) , _lowercase , index=_lowercase )
set_module_tensor_to_device(_lowercase , _lowercase , '''meta''' , dtype=_lowercase , value=torch.empty(*param.size() ) )
| 717 |
def __A ( _lowercase ):
'''simple docstring'''
_A = [0] * len(_lowercase )
_A = []
_A = []
_A = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(_lowercase ) ):
if indegree[i] == 0:
queue.append(_lowercase )
while queue:
_A = queue.pop(0 )
cnt += 1
topo.append(_lowercase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(_lowercase )
if cnt != len(_lowercase ):
print('''Cycle exists''' )
else:
print(_lowercase )
# Adjacency List of Graph
__A = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 62 | 0 |
import argparse
import copy
def __A ( _lowercase ):
'''simple docstring'''
_A = {}
with open(_lowercase ) 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 __A ( _lowercase , _lowercase ):
'''simple docstring'''
with open(_lowercase ) as f:
_A = f.read(1 )
_A = start_node
_A = []
_A = start_node
_A = 0
while visiting not in first_solution:
_A = 1_00_00
for k in dict_of_neighbours[visiting]:
if int(k[1] ) < int(_lowercase ) and k[0] not in first_solution:
_A = k[1]
_A = k[0]
first_solution.append(_lowercase )
_A = distance_of_first_solution + int(_lowercase )
_A = best_node
first_solution.append(_lowercase )
_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_00_00
)
return first_solution, distance_of_first_solution
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = []
for n in solution[1:-1]:
_A = solution.index(_lowercase )
for kn in solution[1:-1]:
_A = solution.index(_lowercase )
if n == kn:
continue
_A = copy.deepcopy(_lowercase )
_A = kn
_A = n
_A = 0
for k in _tmp[:-1]:
_A = _tmp[_tmp.index(_lowercase ) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
_A = distance + int(i[1] )
_tmp.append(_lowercase )
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 _lowercase : x[index_of_last_item_in_the_list] )
return neighborhood_of_solution
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = 1
_A = first_solution
_A = []
_A = distance_of_first_solution
_A = solution
while count <= iters:
_A = find_neighborhood(_lowercase , _lowercase )
_A = 0
_A = neighborhood[index_of_best_solution]
_A = len(_lowercase ) - 1
_A = False
while not found:
_A = 0
while i < len(_lowercase ):
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(_lowercase ) >= size:
tabu_list.pop(0 )
_A = count + 1
return best_solution_ever, best_cost
def __A ( _lowercase=None ):
'''simple docstring'''
_A = generate_neighbours(args.File )
_A ,_A = generate_first_solution(
args.File , _lowercase )
_A ,_A = tabu_search(
_lowercase , _lowercase , _lowercase , args.Iterations , args.Size , )
print(f"""Best solution: {best_sol}, with total distance: {best_cost}.""" )
if __name__ == "__main__":
__A = 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())
| 718 |
import math
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 SchedulerMixin, SchedulerOutput
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = 1
@register_to_config
def __init__( self: Any , __A: int = 10_00 , __A: Optional[Union[np.ndarray, List[float]]] = None ) -> List[str]:
# set `betas`, `alphas`, `timesteps`
self.set_timesteps(__A )
# standard deviation of the initial noise distribution
_A = 1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
_A = 4
# running values
_A = []
def __A ( self: str , __A: int , __A: Union[str, torch.device] = None ) -> int:
_A = num_inference_steps
_A = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
_A = torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
_A = torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
_A = torch.sin(steps * math.pi / 2 ) ** 2
_A = (1.0 - self.betas**2) ** 0.5
_A = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
_A = timesteps.to(__A )
_A = []
def __A ( self: Tuple , __A: torch.FloatTensor , __A: int , __A: torch.FloatTensor , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
_A = (self.timesteps == timestep).nonzero().item()
_A = timestep_index + 1
_A = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(__A )
if len(self.ets ) == 1:
_A = self.ets[-1]
elif len(self.ets ) == 2:
_A = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
_A = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
_A = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
_A = self._get_prev_sample(__A , __A , __A , __A )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Optional[int] , __A: torch.FloatTensor , *__A: Tuple , **__A: List[Any] ) -> torch.FloatTensor:
return sample
def __A ( self: List[str] , __A: Optional[Any] , __A: Optional[Any] , __A: Any , __A: List[Any] ) -> List[Any]:
_A = self.alphas[timestep_index]
_A = self.betas[timestep_index]
_A = self.alphas[prev_timestep_index]
_A = self.betas[prev_timestep_index]
_A = (sample - sigma * ets) / max(__A , 1e-8 )
_A = next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self: List[str] ) -> Dict:
return self.config.num_train_timesteps
| 62 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'facebook/dpr-ctx_encoder-single-nq-base': (
'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json'
),
'facebook/dpr-question_encoder-single-nq-base': (
'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json'
),
'facebook/dpr-reader-single-nq-base': (
'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json'
),
'facebook/dpr-ctx_encoder-multiset-base': (
'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json'
),
'facebook/dpr-question_encoder-multiset-base': (
'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json'
),
'facebook/dpr-reader-multiset-base': (
'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json'
),
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "dpr"
def __init__( self: Union[str, Any] , __A: Dict=3_05_22 , __A: Optional[Any]=7_68 , __A: Union[str, Any]=12 , __A: Optional[int]=12 , __A: Union[str, Any]=30_72 , __A: Dict="gelu" , __A: Optional[Any]=0.1 , __A: Tuple=0.1 , __A: Optional[int]=5_12 , __A: int=2 , __A: List[str]=0.02 , __A: Dict=1e-12 , __A: List[str]=0 , __A: Union[str, Any]="absolute" , __A: int = 0 , **__A: Optional[int] , ) -> Any:
super().__init__(pad_token_id=__A , **__A )
_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 = projection_dim
_A = position_embedding_type
| 719 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A ,_A = len(_lowercase ), len(grid[0] )
if (
min(_lowercase , _lowercase ) < 0
or row == row_length
or col == col_length
or (row, col) in visit
or grid[row][col] == 1
):
return 0
if row == row_length - 1 and col == col_length - 1:
return 1
visit.add((row, col) )
_A = 0
count += depth_first_search(_lowercase , row + 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , row - 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col + 1 , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col - 1 , _lowercase )
visit.remove((row, col) )
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
from __future__ import annotations
import os
import tempfile
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import is_tensorflow_text_available, is_tf_available
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
from ..test_modeling_tf_common import floats_tensor
from .test_framework_agnostic import GenerationIntegrationTestsMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
AutoTokenizer,
TFAutoModelForCausalLM,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSpeechSeqaSeq,
TFAutoModelForVisionaSeq,
TFBartForConditionalGeneration,
TFLogitsProcessorList,
TFMinLengthLogitsProcessor,
tf_top_k_top_p_filtering,
)
if is_tensorflow_text_available():
import tensorflow_text as text
@require_tf
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: str ) -> Optional[int]:
_A = tf.convert_to_tensor(
[
[
8.2_220_991, # 3rd highest value; idx. 0
-0.5_620_044,
5.23_229_752,
4.0_386_393,
-6.8_798_378,
-0.54_785_802,
-3.2_012_153,
2.92_777_176,
1.88_171_953,
7.35_341_276, # 5th highest value; idx. 9
8.43_207_833, # 2nd highest value; idx. 10
-9.85_711_836,
-5.96_209_236,
-1.13_039_161,
-7.1_115_294,
-0.8_369_633,
-5.3_186_408,
7.06_427_407,
0.81_369_344,
-0.82_023_817,
-5.9_179_796,
0.58_813_443,
-6.99_778_438,
4.71_551_189,
-0.18_771_637,
7.44_020_759, # 4th highest value; idx. 25
9.38_450_987, # 1st highest value; idx. 26
2.12_662_941,
-9.32_562_038,
2.35_652_522,
], # cummulative prob of 5 highest values <= 0.6
[
0.58_425_518,
4.53_139_238,
-5.57_510_464,
-6.28_030_699,
-7.19_529_503,
-4.02_122_551,
1.39_337_037,
-6.06_707_057,
1.59_480_517,
-9.643_119,
0.03_907_799,
0.67_231_762,
-8.88_206_726,
6.27_115_922, # 4th highest value; idx. 13
2.28_520_723,
4.82_767_506,
4.30_421_368,
8.8_275_313, # 2nd highest value; idx. 17
5.44_029_958, # 5th highest value; idx. 18
-4.4_735_794,
7.38_579_536, # 3rd highest value; idx. 20
-2.91_051_663,
2.61_946_077,
-2.5_674_762,
-9.48_959_302,
-4.02_922_645,
-1.35_416_918,
9.67_702_323, # 1st highest value; idx. 27
-5.89_478_553,
1.85_370_467,
], # cummulative prob of 5 highest values <= 0.6
] , dtype=tf.floataa , )
_A = tf.convert_to_tensor(
[[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above
_A = tf.convert_to_tensor(
[8.222_099, 7.3_534_126, 8.432_078, 7.4_402_075, 9.38_451, 6.271_159, 8.827_531, 5.4_402_995, 7.3_857_956, 9.677_023] , dtype=tf.floataa , ) # expected non filtered values as noted above
_A = tf_top_k_top_p_filtering(__A , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 )
_A = output[output != -float('''inf''' )]
_A = tf.cast(
tf.where(tf.not_equal(__A , tf.constant(-float('''inf''' ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , )
tf.debugging.assert_near(__A , __A , rtol=1e-12 )
tf.debugging.assert_equal(__A , __A )
@require_tf
class SCREAMING_SNAKE_CASE ( unittest.TestCase , snake_case ):
"""simple docstring"""
if is_tf_available():
A_ = {
"AutoModelForCausalLM": TFAutoModelForCausalLM,
"AutoModelForSpeechSeq2Seq": TFAutoModelForSpeechSeqaSeq,
"AutoModelForSeq2SeqLM": TFAutoModelForSeqaSeqLM,
"AutoModelForVision2Seq": TFAutoModelForVisionaSeq,
"LogitsProcessorList": TFLogitsProcessorList,
"MinLengthLogitsProcessor": TFMinLengthLogitsProcessor,
"create_tensor_fn": tf.convert_to_tensor,
"floats_tensor": floats_tensor,
"return_tensors": "tf",
}
@slow
def __A ( self: int ) -> List[Any]:
# TF-only test: tf.saved_model export
_A = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
_A = 2
_A = 2
class SCREAMING_SNAKE_CASE ( tf.Module ):
"""simple docstring"""
def __init__( self: Tuple , __A: Optional[int] ) -> Dict:
super(__A , self ).__init__()
_A = model
@tf.function(
input_signature=(
tf.TensorSpec((None, input_length) , tf.intaa , name='''input_ids''' ),
tf.TensorSpec((None, input_length) , tf.intaa , name='''attention_mask''' ),
) , jit_compile=__A , )
def __A ( self: Optional[Any] , __A: str , __A: int ) -> Optional[int]:
_A = self.model.generate(
input_ids=__A , attention_mask=__A , max_new_tokens=__A , return_dict_in_generate=__A , )
return {"sequences": outputs["sequences"]}
_A = [[2, 0], [1_02, 1_03]]
_A = [[1, 0], [1, 1]]
_A = DummyModel(model=__A )
with tempfile.TemporaryDirectory() as tmp_dir:
tf.saved_model.save(__A , __A , signatures={'''serving_default''': dummy_model.serving} )
_A = tf.saved_model.load(__A ).signatures['''serving_default''']
for batch_size in range(1 , len(__A ) + 1 ):
_A = {
'''input_ids''': tf.constant(dummy_input_ids[:batch_size] ),
'''attention_mask''': tf.constant(dummy_attention_masks[:batch_size] ),
}
_A = serving_func(**__A )['''sequences''']
_A = test_model.generate(**__A , max_new_tokens=__A )
tf.debugging.assert_equal(__A , __A )
@slow
def __A ( self: List[Any] ) -> List[Any]:
# TF-only test: tf.saved_model export
_A = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
_A = 1
_A = 2
class SCREAMING_SNAKE_CASE ( tf.Module ):
"""simple docstring"""
def __init__( self: Tuple , __A: Union[str, Any] ) -> str:
super(__A , self ).__init__()
_A = model
@tf.function(
input_signature=(
tf.TensorSpec((batch_size, None) , tf.intaa , name='''input_ids''' ),
tf.TensorSpec((batch_size, None) , tf.intaa , name='''attention_mask''' ),
) , jit_compile=__A , )
def __A ( self: int , __A: Dict , __A: Any ) -> str:
_A = self.model.generate(
input_ids=__A , attention_mask=__A , max_new_tokens=__A , return_dict_in_generate=__A , )
return {"sequences": outputs["sequences"]}
_A = [[2], [1_02, 1_03]]
_A = [[1], [1, 1]]
_A = DummyModel(model=__A )
with tempfile.TemporaryDirectory() as tmp_dir:
tf.saved_model.save(__A , __A , signatures={'''serving_default''': dummy_model.serving} )
_A = tf.saved_model.load(__A ).signatures['''serving_default''']
for input_row in range(len(__A ) ):
_A = {
'''input_ids''': tf.constant([dummy_input_ids[input_row]] ),
'''attention_mask''': tf.constant([dummy_attention_masks[input_row]] ),
}
_A = serving_func(**__A )['''sequences''']
_A = test_model.generate(**__A , max_new_tokens=__A )
tf.debugging.assert_equal(__A , __A )
@slow
@require_tensorflow_text
def __A ( self: Optional[Any] ) -> int:
# TF-only test: tf.saved_model export
with tempfile.TemporaryDirectory() as tmp_dir:
# file needed to load the TF tokenizer
hf_hub_download(repo_id='''google/flan-t5-small''' , filename='''spiece.model''' , local_dir=__A )
class SCREAMING_SNAKE_CASE ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self: int ) -> int:
super().__init__()
_A = text.SentencepieceTokenizer(
model=tf.io.gfile.GFile(os.path.join(__A , '''spiece.model''' ) , '''rb''' ).read() )
_A = TFAutoModelForSeqaSeqLM.from_pretrained('''hf-internal-testing/tiny-random-t5''' )
def __A ( self: Dict , __A: Dict , *__A: Any , **__A: int ) -> Any:
_A = self.tokenizer.tokenize(__A )
_A ,_A = text.pad_model_inputs(
__A , max_seq_length=64 , pad_value=self.model.config.pad_token_id )
_A = self.model.generate(input_ids=__A , attention_mask=__A )
return self.tokenizer.detokenize(__A )
_A = CompleteSentenceTransformer()
_A = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name='''inputs''' )
_A = complete_model(__A )
_A = tf.keras.Model(__A , __A )
keras_model.save(__A )
def __A ( self: Dict ) -> List[Any]:
# Has PT equivalent: this test relies on random sampling
_A = {
'''do_sample''': True,
'''num_beams''': 1,
'''top_p''': 0.7,
'''top_k''': 10,
'''temperature''': 0.7,
}
_A = 14
_A = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
_A = '''Hello, my dog is cute and'''
_A = tokenizer(__A , return_tensors='''tf''' )
_A = TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
_A = 6_38
# forces the generation to happen on CPU, to avoid GPU-related quirks
with tf.device(''':/CPU:0''' ):
tf.random.set_seed(0 )
_A = model.generate(**__A , eos_token_id=__A , **__A )
self.assertTrue(expectation == len(generated_tokens[0] ) )
_A = [6_38, 1_98]
with tf.device(''':/CPU:0''' ):
tf.random.set_seed(0 )
_A = model.generate(**__A , eos_token_id=__A , **__A )
self.assertTrue(expectation == len(generated_tokens[0] ) )
def __A ( self: str ) -> str:
# Has PT equivalent: ample use of framework-specific code
_A = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bart''' )
_A = '''Hugging Face is a technology company based in New York and Paris.'''
_A = bart_tokenizer(__A , return_tensors='''tf''' ).input_ids
_A = TFBartForConditionalGeneration.from_pretrained('''hf-internal-testing/tiny-random-bart''' )
_A = bart_model.generate(__A ).numpy()
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Any=None , **__A: Optional[int] ) -> Optional[Any]:
return super().call(__A , **__A )
_A = FakeBart.from_pretrained('''hf-internal-testing/tiny-random-bart''' )
_A = bart_model.generate(__A , foo='''bar''' ).numpy()
self.assertTrue(np.array_equal(__A , __A ) )
class SCREAMING_SNAKE_CASE ( bart_model.model.encoder.__class__ ):
"""simple docstring"""
def __A ( self: List[Any] , __A: Optional[int] , **__A: Union[str, Any] ) -> List[str]:
return super().call(__A , **__A )
_A = FakeEncoder(bart_model.config , bart_model.model.shared )
_A = fake_encoder
# Normal generation still works (the output will be different because the encoder weights are different)
_A = bart_model.generate(__A ).numpy()
with self.assertRaises(__A ):
# FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo"
bart_model.generate(__A , foo='''bar''' )
| 720 |
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
__A = NewType('DataClass', Any)
__A = NewType('DataClassType', Any)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , _lowercase ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError(
f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" )
def __A ( _lowercase ):
'''simple docstring'''
_A = {str(_lowercase ): choice for choice in choices}
return lambda _lowercase : str_to_choice.get(_lowercase , _lowercase )
def __A ( *,
_lowercase = None , _lowercase = None , _lowercase = dataclasses.MISSING , _lowercase = dataclasses.MISSING , _lowercase = None , **_lowercase , ):
'''simple docstring'''
if metadata is None:
# Important, don't use as default param in function signature because dict is mutable and shared across function calls
_A = {}
if aliases is not None:
_A = aliases
if help is not None:
_A = help
return dataclasses.field(metadata=_lowercase , default=_lowercase , default_factory=_lowercase , **_lowercase )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = 42
def __init__( self: Optional[Any] , __A: Union[DataClassType, Iterable[DataClassType]] , **__A: List[Any] ) -> str:
# To make the default appear when using --help
if "formatter_class" not in kwargs:
_A = ArgumentDefaultsHelpFormatter
super().__init__(**__A )
if dataclasses.is_dataclass(__A ):
_A = [dataclass_types]
_A = list(__A )
for dtype in self.dataclass_types:
self._add_dataclass_arguments(__A )
@staticmethod
def __A ( __A: ArgumentParser , __A: dataclasses.Field ) -> str:
_A = f"""--{field.name}"""
_A = field.metadata.copy()
# field.metadata is not used at all by Data Classes,
# it is provided as a third-party extension mechanism.
if isinstance(field.type , __A ):
raise RuntimeError(
'''Unresolved type detected, which should have been done with the help of '''
'''`typing.get_type_hints` method by default''' )
_A = kwargs.pop('''aliases''' , [] )
if isinstance(__A , __A ):
_A = [aliases]
_A = getattr(field.type , '''__origin__''' , field.type )
if origin_type is Union or (hasattr(__A , '''UnionType''' ) and isinstance(__A , types.UnionType )):
if str not in field.type.__args__ and (
len(field.type.__args__ ) != 2 or type(__A ) not in field.type.__args__
):
raise ValueError(
'''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
''' the argument parser only supports one type per argument.'''
f""" Problem encountered in field '{field.name}'.""" )
if type(__A ) not in field.type.__args__:
# filter `str` in Union
_A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
_A = getattr(field.type , '''__origin__''' , field.type )
elif bool not in field.type.__args__:
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
_A = (
field.type.__args__[0] if isinstance(__A , field.type.__args__[1] ) else field.type.__args__[1]
)
_A = getattr(field.type , '''__origin__''' , field.type )
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
_A = {}
if origin_type is Literal or (isinstance(field.type , __A ) and issubclass(field.type , __A )):
if origin_type is Literal:
_A = field.type.__args__
else:
_A = [x.value for x in field.type]
_A = make_choice_type_function(kwargs['''choices'''] )
if field.default is not dataclasses.MISSING:
_A = field.default
else:
_A = True
elif field.type is bool or field.type == Optional[bool]:
# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
_A = copy(__A )
# Hack because type=bool in argparse does not behave as we want.
_A = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
_A = False if field.default is dataclasses.MISSING else field.default
# This is the value that will get picked if we don't include --field_name in any way
_A = default
# This tells argparse we accept 0 or 1 value after --field_name
_A = '''?'''
# This is the value that will get picked if we do --field_name (without value)
_A = True
elif isclass(__A ) and issubclass(__A , __A ):
_A = field.type.__args__[0]
_A = '''+'''
if field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
elif field.default is dataclasses.MISSING:
_A = True
else:
_A = field.type
if field.default is not dataclasses.MISSING:
_A = field.default
elif field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
else:
_A = True
parser.add_argument(__A , *__A , **__A )
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need those changes/additional keys.
if field.default is True and (field.type is bool or field.type == Optional[bool]):
_A = False
parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__A )
def __A ( self: Dict , __A: DataClassType ) -> List[Any]:
if hasattr(__A , '''_argument_group_name''' ):
_A = self.add_argument_group(dtype._argument_group_name )
else:
_A = self
try:
_A = get_type_hints(__A )
except NameError:
raise RuntimeError(
f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
'''removing line of `from __future__ import annotations` which opts in Postponed '''
'''Evaluation of Annotations (PEP 563)''' )
except TypeError as ex:
# Remove this block when we drop Python 3.9 support
if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__A ):
_A = '''.'''.join(map(__A , sys.version_info[:3] ) )
raise RuntimeError(
f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
'''line of `from __future__ import annotations` which opts in union types as '''
'''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
'''support Python versions that lower than 3.10, you need to use '''
'''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
'''`X | None`.''' ) from ex
raise
for field in dataclasses.fields(__A ):
if not field.init:
continue
_A = type_hints[field.name]
self._parse_dataclass_field(__A , __A )
def __A ( self: int , __A: Any=None , __A: int=False , __A: Any=True , __A: Optional[Any]=None , __A: Any=None , ) -> Tuple[DataClass, ...]:
if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )):
_A = []
if args_filename:
args_files.append(Path(__A ) )
elif look_for_args_file and len(sys.argv ):
args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) )
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
_A = ArgumentParser()
args_file_parser.add_argument(__A , type=__A , action='''append''' )
# Use only remaining args for further parsing (remove the args_file_flag)
_A ,_A = args_file_parser.parse_known_args(args=__A )
_A = vars(__A ).get(args_file_flag.lstrip('''-''' ) , __A )
if cmd_args_file_paths:
args_files.extend([Path(__A ) for p in cmd_args_file_paths] )
_A = []
for args_file in args_files:
if args_file.exists():
file_args += args_file.read_text().split()
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
_A = file_args + args if args is not None else file_args + sys.argv[1:]
_A ,_A = self.parse_known_args(args=__A )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in vars(__A ).items() if k in keys}
for k in keys:
delattr(__A , __A )
_A = dtype(**__A )
outputs.append(__A )
if len(namespace.__dict__ ) > 0:
# additional namespace.
outputs.append(__A )
if return_remaining_strings:
return (*outputs, remaining_args)
else:
if remaining_args:
raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" )
return (*outputs,)
def __A ( self: Tuple , __A: Dict[str, Any] , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = set(args.keys() )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in args.items() if k in keys}
unused_keys.difference_update(inputs.keys() )
_A = dtype(**__A )
outputs.append(__A )
if not allow_extra_keys and unused_keys:
raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__A )}""" )
return tuple(__A )
def __A ( self: Tuple , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
with open(Path(__A ) , encoding='''utf-8''' ) as open_json_file:
_A = json.loads(open_json_file.read() )
_A = self.parse_dict(__A , allow_extra_keys=__A )
return tuple(__A )
def __A ( self: List[Any] , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = self.parse_dict(yaml.safe_load(Path(__A ).read_text() ) , allow_extra_keys=__A )
return tuple(__A )
| 62 | 0 |
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
__A = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "sequence-classification"
def __init__( self: str , __A: Union[str, Any] ) -> List[str]:
if type(__A ) == dict:
_A = Namespace(**__A )
_A = glue_output_modes[hparams.task]
_A = glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def __A ( self: Optional[Any] , **__A: Union[str, Any] ) -> Optional[int]:
return self.model(**__A )
def __A ( self: Any , __A: Union[str, Any] , __A: int ) -> Optional[Any]:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A = outputs[0]
_A = self.trainer.lr_schedulers[0]['''scheduler''']
_A = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def __A ( self: List[str] ) -> Dict:
_A = self.hparams
_A = processors[args.task]()
_A = processor.get_labels()
for mode in ["train", "dev"]:
_A = self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('''Loading features from cached file %s''' , __A )
else:
logger.info('''Creating features from dataset file at %s''' , args.data_dir )
_A = (
processor.get_dev_examples(args.data_dir )
if mode == '''dev'''
else processor.get_train_examples(args.data_dir )
)
_A = convert_examples_to_features(
__A , 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''' , __A )
torch.save(__A , __A )
def __A ( self: List[str] , __A: str , __A: int , __A: bool = False ) -> DataLoader:
_A = '''dev''' if mode == '''test''' else mode
_A = self._feature_file(__A )
logger.info('''Loading features from cached file %s''' , __A )
_A = torch.load(__A )
_A = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_A = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_A = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_A = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_A = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def __A ( self: List[str] , __A: str , __A: Tuple ) -> str:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A ,_A = outputs[:2]
_A = logits.detach().cpu().numpy()
_A = inputs['''labels'''].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __A ( self: str , __A: Dict ) -> tuple:
_A = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item()
_A = np.concatenate([x['''pred'''] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_A = np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_A = np.squeeze(__A )
_A = np.concatenate([x['''target'''] for x in outputs] , axis=0 )
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_A = dict(results.items() )
_A = results
return ret, preds_list, out_label_list
def __A ( self: Any , __A: list ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = ret['''log''']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __A ( self: int , __A: Union[str, Any] ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = 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 ( __A: Optional[Any] , __A: Optional[Any] ) -> Optional[Any]:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'''--max_seq_length''' , default=1_28 , type=__A , 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=__A , required=__A , help='''The GLUE task to run''' , )
parser.add_argument(
'''--gpus''' , default=0 , type=__A , 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 __A ( ):
_A = argparse.ArgumentParser()
add_generic_args(_lowercase , os.getcwd() )
_A = GLUETransformer.add_model_specific_args(_lowercase , os.getcwd() )
_A = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_A = os.path.join(
'''./results''' , f"""{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}""" , )
os.makedirs(args.output_dir )
_A = GLUETransformer(_lowercase )
_A = generic_train(_lowercase , _lowercase )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_A = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=_lowercase ) )
_A = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(_lowercase )
if __name__ == "__main__":
main()
| 721 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: Union[str, Any] , __A: int=2 , __A: List[str]=True , __A: List[Any]=False , __A: Union[str, Any]=10 , __A: Optional[int]=3 , __A: List[Any]=32 * 4 , __A: Dict=32 * 6 , __A: Optional[Any]=4 , __A: Any=32 , ) -> str:
_A = parent
_A = batch_size
_A = is_training
_A = use_auxiliary_loss
_A = num_queries
_A = num_channels
_A = min_size
_A = max_size
_A = num_labels
_A = mask_feature_size
def __A ( self: Dict ) -> Optional[int]:
_A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
__A )
_A = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A )
_A = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5
).float()
_A = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long()
_A = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __A ( self: Optional[Any] ) -> Tuple:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __A ( self: Dict ) -> Tuple:
_A ,_A ,_A ,_A ,_A = self.prepare_config_and_inputs()
_A = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: Dict ) -> int:
_A = output.encoder_hidden_states
_A = output.pixel_decoder_hidden_states
_A = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , config.decoder_config.decoder_layers )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Any , __A: Dict=False ) -> Any:
with torch.no_grad():
_A = MaskFormerModel(config=__A )
model.to(__A )
model.eval()
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A , output_hidden_states=__A )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(__A , __A )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Union[str, Any] , __A: Union[str, Any] , __A: List[Any] ) -> int:
_A = MaskFormerForInstanceSegmentation(config=__A )
model.to(__A )
model.eval()
def comm_check_on_output(__A: int ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A )
comm_check_on_output(__A )
_A = model(
pixel_values=__A , pixel_mask=__A , mask_labels=__A , class_labels=__A )
comm_check_on_output(__A )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
A_ = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
A_ = False
A_ = False
A_ = False
A_ = False
def __A ( self: int ) -> Tuple:
_A = MaskFormerModelTester(self )
_A = ConfigTester(self , config_class=__A , has_text_modality=__A )
def __A ( self: List[Any] ) -> Dict:
self.config_tester.run_common_tests()
def __A ( self: Optional[Any] ) -> int:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Dict ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__A )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def __A ( self: int ) -> Tuple:
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def __A ( self: List[Any] ) -> Any:
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def __A ( self: Union[str, Any] ) -> Optional[int]:
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def __A ( self: int ) -> List[str]:
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def __A ( self: Union[str, Any] ) -> List[Any]:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: List[Any] ) -> Any:
pass
def __A ( self: Dict ) -> Optional[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A )
_A = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_A = [*signature.parameters.keys()]
_A = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __A )
@slow
def __A ( self: int ) -> Optional[Any]:
for model_name in ["facebook/maskformer-swin-small-coco"]:
_A = MaskFormerModel.from_pretrained(__A )
self.assertIsNotNone(__A )
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = (self.model_tester.min_size,) * 2
_A = {
'''pixel_values''': torch.randn((2, 3, *size) , device=__A ),
'''mask_labels''': torch.randn((2, 10, *size) , device=__A ),
'''class_labels''': torch.zeros(2 , 10 , device=__A ).long(),
}
_A = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__A )
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
def __A ( self: Optional[Any] ) -> List[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Any ) -> Tuple:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A ).to(__A )
_A = model(**__A , output_attentions=__A )
self.assertTrue(outputs.attentions is not None )
def __A ( self: Dict ) -> Union[str, Any]:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A ).loss
loss.backward()
def __A ( self: Tuple ) -> Optional[Any]:
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = True
_A = True
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A )
_A = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
_A = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
_A = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
_A = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=__A )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__A = 1e-4
def __A ( ):
'''simple docstring'''
_A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self: Union[str, Any] ) -> Optional[int]:
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def __A ( self: List[Any] ) -> Any:
_A = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(__A )
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
_A = torch.tensor(
[[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Dict ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [
[-1.3_737_124, -1.7_724_937, -1.9_364_233],
[-1.5_977_281, -1.9_867_939, -2.1_523_695],
[-1.5_795_398, -1.9_269_832, -2.093_942],
]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: List[Any] ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Optional[Any] ) -> str:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors='''pt''' , )
_A = inputs['''pixel_values'''].to(__A )
_A = [el.to(__A ) for el in inputs['''mask_labels''']]
_A = [el.to(__A ) for el in inputs['''class_labels''']]
with torch.no_grad():
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
| 62 | 0 |
import argparse
import json
import os
import fairseq
import torch
from torch import nn
from transformers import (
SpeechaTextaConfig,
SpeechaTextaForCausalLM,
SpeechaTextaTokenizer,
SpeechEncoderDecoderConfig,
SpeechEncoderDecoderModel,
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaModel,
logging,
)
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
__A = {
'post_extract_proj': 'feature_projection.projection',
'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
'fc2': 'encoder.layers.*.feed_forward.output_dense',
'final_layer_norm': 'encoder.layers.*.final_layer_norm',
'encoder.layer_norm': 'encoder.layer_norm',
'w2v_model.layer_norm': 'feature_projection.layer_norm',
'quantizer.weight_proj': 'quantizer.weight_proj',
'quantizer.vars': 'quantizer.codevectors',
'project_q': 'project_q',
'final_proj': 'project_hid',
'w2v_encoder.proj': 'lm_head',
'mask_emb': 'masked_spec_embed',
}
__A = [
'lm_head',
'quantizer.weight_proj',
'quantizer.codevectors',
'project_q',
'project_hid',
]
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
for attribute in key.split('''.''' ):
_A = getattr(_lowercase , _lowercase )
if weight_type is not None:
_A = getattr(_lowercase , _lowercase ).shape
else:
_A = hf_pointer.shape
assert hf_shape == value.shape, (
f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be"""
f""" {value.shape} for {full_name}"""
)
if weight_type == "weight":
_A = value
elif weight_type == "weight_g":
_A = value
elif weight_type == "weight_v":
_A = value
elif weight_type == "bias":
_A = value
else:
_A = value
logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = []
_A = fairseq_model.state_dict()
_A = hf_model.feature_extractor
# if encoder has different dim to decoder -> use proj_weight
_A = None
for name, value in fairseq_dict.items():
_A = False
if "conv_layers" in name:
load_conv_layer(
_lowercase , _lowercase , _lowercase , _lowercase , hf_model.config.feat_extract_norm == '''group''' , )
_A = True
elif name.split('''.''' )[0] == "proj":
_A = fairseq_model.proj
_A = True
else:
for key, mapped_key in MAPPING.items():
if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]:
_A = True
if "*" in mapped_key:
_A = name.split(_lowercase )[0].split('''.''' )[-2]
_A = mapped_key.replace('''*''' , _lowercase )
if "weight_g" in name:
_A = '''weight_g'''
elif "weight_v" in name:
_A = '''weight_v'''
elif "bias" in name:
_A = '''bias'''
elif "weight" in name:
_A = '''weight'''
else:
_A = None
set_recursively(_lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
continue
if not is_used:
unused_weights.append(_lowercase )
logger.warning(f"""Unused weights: {unused_weights}""" )
return proj_weight
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = full_name.split('''conv_layers.''' )[-1]
_A = name.split('''.''' )
_A = int(items[0] )
_A = int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""
)
_A = value
logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""
)
_A = value
logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"""
" found."
)
_A = value
logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""
)
_A = value
logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A ,_A = emb.weight.shape
_A = nn.Linear(_lowercase , _lowercase , bias=_lowercase )
_A = emb.weight.data
return lin_layer
def __A ( _lowercase ):
'''simple docstring'''
with open(_lowercase , '''r''' , encoding='''utf-8''' ) as f:
_A = f.readlines()
_A = [line.split(''' ''' )[0] for line in lines]
_A = len(_lowercase )
_A = {
'''<s>''': 0,
'''<pad>''': 1,
'''</s>''': 2,
'''<unk>''': 3,
}
vocab_dict.update(dict(zip(_lowercase , range(4 , num_words + 4 ) ) ) )
return vocab_dict
@torch.no_grad()
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ):
'''simple docstring'''
_A = WavaVecaConfig.from_pretrained(_lowercase )
_A = SpeechaTextaConfig.from_pretrained(
_lowercase , vocab_size=_lowercase , decoder_layers=_lowercase , do_stable_layer_norm=_lowercase )
_A = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=_lowercase , return_attention_mask=_lowercase , )
_A ,_A ,_A = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} )
_A = model[0].eval()
# set weights for wav2vec2 encoder
_A = WavaVecaModel(_lowercase )
_A = recursively_load_weights_wavaveca(model.encoder , _lowercase )
_A = SpeechaTextaForCausalLM(_lowercase )
_A ,_A = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=_lowercase )
# set output linear layer
unexpected_keys.remove('''embed_out''' )
_A = nn.Parameter(model.decoder.embed_out.detach() )
# layer norm is init to identity matrix so leaving it is fine
logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" )
logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" )
_A = SpeechEncoderDecoderModel(encoder=_lowercase , decoder=_lowercase )
_A = False
# add projection layer
_A = nn.Parameter(projection_layer.weight )
_A = nn.Parameter(projection_layer.bias )
_A = create_vocab_dict(_lowercase )
with open(os.path.join(_lowercase , '''vocab.json''' ) , '''w''' ) as fp:
json.dump(_lowercase , _lowercase )
_A = SpeechaTextaTokenizer(os.path.join(_lowercase , '''vocab.json''' ) )
tokenizer.save_pretrained(_lowercase )
_A = hf_wavavec.config.to_dict()
_A = tokenizer.pad_token_id
_A = tokenizer.bos_token_id
_A = tokenizer.eos_token_id
_A = '''speech_to_text_2'''
_A = '''wav2vec2'''
_A = SpeechEncoderDecoderConfig.from_dict(_lowercase )
hf_wavavec.save_pretrained(_lowercase )
feature_extractor.save_pretrained(_lowercase )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
parser.add_argument(
'--encoder_config_path',
default='facebook/wav2vec2-large-lv60',
type=str,
help='Path to hf encoder wav2vec2 checkpoint config',
)
parser.add_argument(
'--decoder_config_path',
default='facebook/s2t-small-mustc-en-fr-st',
type=str,
help='Path to hf decoder s2t checkpoint config',
)
parser.add_argument('--vocab_size', default=10224, type=int, help='Vocab size of decoder')
parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers')
__A = parser.parse_args()
convert_wavaveca_checkpoint(
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.dict_path,
encoder_config_path=args.encoder_config_path,
decoder_config_path=args.decoder_config_path,
vocab_size=args.vocab_size,
num_decoder_layers=args.num_decoder_layers,
)
| 700 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Optional[int] , __A: Optional[Any] ) -> str:
_A = question_encoder
_A = generator
_A = self.question_encoder
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Dict:
if os.path.isfile(__A ):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(__A , exist_ok=__A )
_A = os.path.join(__A , '''question_encoder_tokenizer''' )
_A = os.path.join(__A , '''generator_tokenizer''' )
self.question_encoder.save_pretrained(__A )
self.generator.save_pretrained(__A )
@classmethod
def __A ( cls: Optional[Any] , __A: List[str] , **__A: int ) -> Any:
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
_A = kwargs.pop('''config''' , __A )
if config is None:
_A = RagConfig.from_pretrained(__A )
_A = AutoTokenizer.from_pretrained(
__A , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' )
_A = AutoTokenizer.from_pretrained(
__A , config=config.generator , subfolder='''generator_tokenizer''' )
return cls(question_encoder=__A , generator=__A )
def __call__( self: int , *__A: Optional[int] , **__A: List[str] ) -> int:
return self.current_tokenizer(*__A , **__A )
def __A ( self: Dict , *__A: List[str] , **__A: List[str] ) -> Dict:
return self.generator.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Tuple , **__A: List[str] ) -> Tuple:
return self.generator.decode(*__A , **__A )
def __A ( self: Dict ) -> List[str]:
_A = self.question_encoder
def __A ( self: Union[str, Any] ) -> int:
_A = self.generator
def __A ( self: Dict , __A: List[str] , __A: Optional[List[str]] = None , __A: Optional[int] = None , __A: Optional[int] = None , __A: str = "longest" , __A: str = None , __A: bool = True , **__A: Tuple , ) -> BatchEncoding:
warnings.warn(
'''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
'''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
'''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
'''details''' , __A , )
if max_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
__A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , )
_A = labels['''input_ids''']
return model_inputs
| 62 | 0 |
__A = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
__A = ['a', 'b', 'c', 'd', 'e']
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = start
# add current to visited
visited.append(_lowercase )
_A = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
_A = topological_sort(_lowercase , _lowercase , _lowercase )
# if all neighbors visited add current to sort
sort.append(_lowercase )
# if all vertices haven't been visited select a new one to visit
if len(_lowercase ) != len(_lowercase ):
for vertice in vertices:
if vertice not in visited:
_A = topological_sort(_lowercase , _lowercase , _lowercase )
# return sort
return sort
if __name__ == "__main__":
__A = topological_sort('a', [], [])
print(sort)
| 701 |
from __future__ import annotations
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ): # noqa: E741
'''simple docstring'''
while r - l > 1:
_A = (l + r) // 2
if v[m] >= key:
_A = m
else:
_A = m # noqa: E741
return r
def __A ( _lowercase ):
'''simple docstring'''
if len(_lowercase ) == 0:
return 0
_A = [0] * len(_lowercase )
_A = 1
_A = v[0]
for i in range(1 , len(_lowercase ) ):
if v[i] < tail[0]:
_A = v[i]
elif v[i] > tail[length - 1]:
_A = v[i]
length += 1
else:
_A = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
__A = 8.314_462 # Unit - J mol-1 K-1
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or volume < 0:
raise ValueError('''Invalid inputs. Enter positive value.''' )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if moles < 0 or kelvin < 0 or pressure < 0:
raise ValueError('''Invalid inputs. Enter positive value.''' )
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
if __name__ == "__main__":
from doctest import testmod
testmod()
| 702 |
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
__A = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "sequence-classification"
def __init__( self: str , __A: Union[str, Any] ) -> List[str]:
if type(__A ) == dict:
_A = Namespace(**__A )
_A = glue_output_modes[hparams.task]
_A = glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def __A ( self: Optional[Any] , **__A: Union[str, Any] ) -> Optional[int]:
return self.model(**__A )
def __A ( self: Any , __A: Union[str, Any] , __A: int ) -> Optional[Any]:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A = outputs[0]
_A = self.trainer.lr_schedulers[0]['''scheduler''']
_A = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def __A ( self: List[str] ) -> Dict:
_A = self.hparams
_A = processors[args.task]()
_A = processor.get_labels()
for mode in ["train", "dev"]:
_A = self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('''Loading features from cached file %s''' , __A )
else:
logger.info('''Creating features from dataset file at %s''' , args.data_dir )
_A = (
processor.get_dev_examples(args.data_dir )
if mode == '''dev'''
else processor.get_train_examples(args.data_dir )
)
_A = convert_examples_to_features(
__A , 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''' , __A )
torch.save(__A , __A )
def __A ( self: List[str] , __A: str , __A: int , __A: bool = False ) -> DataLoader:
_A = '''dev''' if mode == '''test''' else mode
_A = self._feature_file(__A )
logger.info('''Loading features from cached file %s''' , __A )
_A = torch.load(__A )
_A = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_A = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_A = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_A = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_A = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def __A ( self: List[str] , __A: str , __A: Tuple ) -> str:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A ,_A = outputs[:2]
_A = logits.detach().cpu().numpy()
_A = inputs['''labels'''].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __A ( self: str , __A: Dict ) -> tuple:
_A = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item()
_A = np.concatenate([x['''pred'''] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_A = np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_A = np.squeeze(__A )
_A = np.concatenate([x['''target'''] for x in outputs] , axis=0 )
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_A = dict(results.items() )
_A = results
return ret, preds_list, out_label_list
def __A ( self: Any , __A: list ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = ret['''log''']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __A ( self: int , __A: Union[str, Any] ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = 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 ( __A: Optional[Any] , __A: Optional[Any] ) -> Optional[Any]:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'''--max_seq_length''' , default=1_28 , type=__A , 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=__A , required=__A , help='''The GLUE task to run''' , )
parser.add_argument(
'''--gpus''' , default=0 , type=__A , 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 __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser()
add_generic_args(_lowercase , os.getcwd() )
_A = GLUETransformer.add_model_specific_args(_lowercase , os.getcwd() )
_A = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_A = os.path.join(
'''./results''' , f"""{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}""" , )
os.makedirs(args.output_dir )
_A = GLUETransformer(_lowercase )
_A = generic_train(_lowercase , _lowercase )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_A = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=_lowercase ) )
_A = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(_lowercase )
if __name__ == "__main__":
main()
| 62 | 0 |
import operator as op
def __A ( _lowercase ):
'''simple docstring'''
_A = []
_A = lambda _lowercase , _lowercase : int(x / y ) # noqa: E731 integer division operation
_A = {
'''^''': op.pow,
'''*''': op.mul,
'''/''': div,
'''+''': op.add,
'''-''': op.sub,
} # operators & their respective operation
# print table header
print('''Symbol'''.center(8 ) , '''Action'''.center(12 ) , '''Stack''' , sep=''' | ''' )
print('''-''' * (30 + len(_lowercase )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(_lowercase ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ('''push(''' + x + ''')''').ljust(12 ) , ''','''.join(_lowercase ) , sep=''' | ''' )
else:
_A = stack.pop() # pop stack
# output in tabular format
print(''''''.rjust(8 ) , ('''pop(''' + b + ''')''').ljust(12 ) , ''','''.join(_lowercase ) , sep=''' | ''' )
_A = stack.pop() # pop stack
# output in tabular format
print(''''''.rjust(8 ) , ('''pop(''' + a + ''')''').ljust(12 ) , ''','''.join(_lowercase ) , sep=''' | ''' )
stack.append(
str(opr[x](int(_lowercase ) , int(_lowercase ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ('''push(''' + a + x + b + ''')''').ljust(12 ) , ''','''.join(_lowercase ) , sep=''' | ''' , )
return int(stack[0] )
if __name__ == "__main__":
__A = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ')
print('\n\tResult = ', solve(Postfix))
| 703 |
from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def __A ( _lowercase = "" ):
'''simple docstring'''
_A = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250'''
_A = BeautifulSoup(requests.get(_lowercase ).text , '''html.parser''' )
_A = soup.find_all('''td''' , attrs='''titleColumn''' )
_A = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' )
return {
title.a.text: float(rating.strong.text )
for title, rating in zip(_lowercase , _lowercase )
}
def __A ( _lowercase = "IMDb_Top_250_Movies.csv" ):
'''simple docstring'''
_A = get_imdb_top_aaa_movies()
with open(_lowercase , '''w''' , newline='''''' ) as out_file:
_A = csv.writer(_lowercase )
writer.writerow(['''Movie title''', '''IMDb rating'''] )
for title, rating in movies.items():
writer.writerow([title, rating] )
if __name__ == "__main__":
write_movies()
| 62 | 0 |
import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
embed_questions_for_retrieval,
make_qa_sas_model,
qa_sas_generate,
query_es_index,
query_qa_dense_index,
)
import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer
__A = 'bart'
__A = True
@st.cache(allow_output_mutation=_lowercase )
def __A ( ):
'''simple docstring'''
if LOAD_DENSE_INDEX:
_A = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' )
_A = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' )
_A = qar_model.eval()
else:
_A ,_A = (None, None)
if MODEL_TYPE == "bart":
_A = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' )
_A = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' )
_A = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' )
sas_model.load_state_dict(save_dict['''model'''] )
_A = sas_model.eval()
else:
_A ,_A = make_qa_sas_model(
model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' )
return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)
@st.cache(allow_output_mutation=_lowercase )
def __A ( ):
'''simple docstring'''
if LOAD_DENSE_INDEX:
_A = faiss.StandardGpuResources()
_A = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train''']
_A = np.memmap(
'''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 1_28) , )
_A = faiss.IndexFlatIP(1_28 )
_A = faiss.index_cpu_to_gpu(_lowercase , 1 , _lowercase )
wikiaab_gpu_index_flat.add(_lowercase ) # TODO fix for larger GPU
else:
_A ,_A = (None, None)
_A = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] )
return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)
@st.cache(allow_output_mutation=_lowercase )
def __A ( ):
'''simple docstring'''
_A = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' )
_A = elia['''train_eli5''']
_A = np.memmap(
'''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 1_28) )
_A = faiss.IndexFlatIP(1_28 )
eli5_train_q_index.add(_lowercase )
return (elia_train, eli5_train_q_index)
__A , __A , __A = load_indexes()
__A , __A , __A , __A = load_models()
__A , __A = load_train_data()
def __A ( _lowercase , _lowercase=10 ):
'''simple docstring'''
_A = embed_questions_for_retrieval([question] , _lowercase , _lowercase )
_A ,_A = eli5_train_q_index.search(_lowercase , _lowercase )
_A = [elia_train[int(_lowercase )] for i in I[0]]
return nn_examples
def __A ( _lowercase , _lowercase="wiki40b" , _lowercase="dense" , _lowercase=10 ):
'''simple docstring'''
if source == "none":
_A ,_A = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), [])
else:
if method == "dense":
_A ,_A = query_qa_dense_index(
_lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
else:
_A ,_A = query_es_index(
_lowercase , _lowercase , index_name='''english_wiki40b_snippets_100w''' , n_results=_lowercase , )
_A = [
(res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst
]
_A = '''question: {} context: {}'''.format(_lowercase , _lowercase )
return question_doc, support_list
@st.cache(
hash_funcs={
torch.Tensor: (lambda _lowercase : None),
transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowercase : None),
} )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase=64 , _lowercase=2_56 , _lowercase=False , _lowercase=2 , _lowercase=0.95 , _lowercase=0.8 ):
'''simple docstring'''
with torch.no_grad():
_A = qa_sas_generate(
_lowercase , _lowercase , _lowercase , num_answers=1 , num_beams=_lowercase , min_len=_lowercase , max_len=_lowercase , do_sample=_lowercase , temp=_lowercase , top_p=_lowercase , top_k=_lowercase , max_input_length=10_24 , device='''cuda:0''' , )[0]
return (answer, support_list)
st.title('Long Form Question Answering with ELI5')
# Start sidebar
__A = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>'
__A = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % (
header_html,
)
st.sidebar.markdown(
header_full,
unsafe_allow_html=True,
)
# Long Form QA with ELI5 and Wikipedia
__A = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n'
st.sidebar.markdown(description, unsafe_allow_html=True)
__A = [
'Answer the question',
'View the retrieved document only',
'View the most similar ELI5 question and answer',
'Show me everything, please!',
]
__A = st.sidebar.checkbox('Demo options')
if demo_options:
__A = st.sidebar.selectbox(
'',
action_list,
index=3,
)
__A = action_list.index(action_st)
__A = st.sidebar.selectbox(
'',
['Show full text of passages', 'Show passage section titles'],
index=0,
)
__A = show_type == 'Show full text of passages'
else:
__A = 3
__A = True
__A = st.sidebar.checkbox('Retrieval options')
if retrieval_options:
__A = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n '
st.sidebar.markdown(retriever_info)
__A = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none'])
__A = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed'])
else:
__A = 'wiki40b'
__A = 'dense'
__A = 'beam'
__A = 2
__A = 64
__A = 256
__A = None
__A = None
__A = st.sidebar.checkbox('Generation options')
if generate_options:
__A = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n '
st.sidebar.markdown(generate_info)
__A = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled'])
__A = st.sidebar.slider(
'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None
)
__A = st.sidebar.slider(
'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None
)
if sampled == "beam":
__A = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None)
else:
__A = st.sidebar.slider(
'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
)
__A = st.sidebar.slider(
'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
)
__A = None
# start main text
__A = [
'<MY QUESTION>',
'How do people make chocolate?',
'Why do we get a fever when we are sick?',
'How can different animals perceive different colors?',
'What is natural language processing?',
'What\'s the best way to treat a sunburn?',
'What exactly are vitamins ?',
'How does nuclear energy provide electricity?',
'What\'s the difference between viruses and bacteria?',
'Why are flutes classified as woodwinds when most of them are made out of metal ?',
'Why do people like drinking coffee even though it tastes so bad?',
'What happens when wine ages? How does it make the wine taste better?',
'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?',
'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?',
'How does New Zealand have so many large bird predators?',
]
__A = st.selectbox(
'What would you like to ask? ---- select <MY QUESTION> to enter a new query',
questions_list,
index=1,
)
if question_s == "<MY QUESTION>":
__A = st.text_input('Enter your question here:', '')
else:
__A = question_s
if st.button('Show me!'):
if action in [0, 1, 3]:
if index_type == "mixed":
__A , __A = make_support(question, source=wiki_source, method='dense', n_results=10)
__A , __A = make_support(question, source=wiki_source, method='sparse', n_results=10)
__A = []
for res_d, res_s in zip(support_list_dense, support_list_sparse):
if tuple(res_d) not in support_list:
support_list += [tuple(res_d)]
if tuple(res_s) not in support_list:
support_list += [tuple(res_s)]
__A = support_list[:10]
__A = '<P> ' + ' <P> '.join([res[-1] for res in support_list])
else:
__A , __A = make_support(question, source=wiki_source, method=index_type, n_results=10)
if action in [0, 3]:
__A , __A = answer_question(
question_doc,
sas_model,
sas_tokenizer,
min_len=min_len,
max_len=int(max_len),
sampling=(sampled == 'sampled'),
n_beams=n_beams,
top_p=top_p,
temp=temp,
)
st.markdown('### The model generated answer is:')
st.write(answer)
if action in [0, 1, 3] and wiki_source != "none":
st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:')
for i, res in enumerate(support_list):
__A = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_'))
__A = res[1].strip()
if sec_titles == "":
__A = '[{}]({})'.format(res[0], wiki_url)
else:
__A = sec_titles.split(' & ')
__A = ' & '.join(
['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list]
)
st.markdown(
'{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections),
unsafe_allow_html=True,
)
if show_passages:
st.write(
'> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True
)
if action in [2, 3]:
__A = find_nearest_training(question)
__A = nn_train_list[0]
st.markdown(
'--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title'])
)
__A = [
'{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != '']))
for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score']))
if i == 0 or sc > 2
]
st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st)))
__A = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n'
st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
| 704 |
import json
import os
import unittest
from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
VOCAB_FILES_NAMES,
BlenderbotSmallTokenizer,
)
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = BlenderbotSmallTokenizer
A_ = False
def __A ( self: List[str] ) -> int:
super().setUp()
_A = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__''']
_A = dict(zip(__A , range(len(__A ) ) ) )
_A = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', '''''']
_A = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''}
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_A = 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 __A ( self: str , **__A: Optional[Any] ) -> Dict:
kwargs.update(self.special_tokens_map )
return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__A )
def __A ( self: str , __A: List[str] ) -> int:
_A = '''adapt act apte'''
_A = '''adapt act apte'''
return input_text, output_text
def __A ( self: Union[str, Any] ) -> Any:
_A = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_A = '''adapt act apte'''
_A = ['''adapt''', '''act''', '''ap@@''', '''te''']
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , __A )
_A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
_A = [0, 1, 2, 3, 4, 5]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
def __A ( self: Any ) -> List[str]:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
assert tok('''sam''' ).input_ids == [13_84]
_A = '''I am a small frog.'''
_A = tok([src_text] , padding=__A , truncation=__A )['''input_ids''']
_A = tok.batch_decode(__A , skip_special_tokens=__A , clean_up_tokenization_spaces=__A )[0]
assert src_text != decoded # I wish it did!
assert decoded == "i am a small frog ."
def __A ( self: Any ) -> int:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
_A = '''I am a small frog .'''
_A = '''.'''
_A = tok(__A )['''input_ids''']
_A = tok(__A )['''input_ids''']
assert encoded[-1] == encoded_dot[0]
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {
'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'LILT_PRETRAINED_MODEL_ARCHIVE_LIST',
'LiltForQuestionAnswering',
'LiltForSequenceClassification',
'LiltForTokenClassification',
'LiltModel',
'LiltPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_lilt import (
LILT_PRETRAINED_MODEL_ARCHIVE_LIST,
LiltForQuestionAnswering,
LiltForSequenceClassification,
LiltForTokenClassification,
LiltModel,
LiltPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 705 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json',
'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "roberta"
def __init__( self: Dict , __A: int=5_02_65 , __A: Union[str, Any]=7_68 , __A: Union[str, Any]=12 , __A: str=12 , __A: int=30_72 , __A: str="gelu" , __A: Union[str, Any]=0.1 , __A: int=0.1 , __A: Optional[int]=5_12 , __A: Union[str, Any]=2 , __A: str=0.02 , __A: str=1e-12 , __A: Any=1 , __A: str=0 , __A: Any=2 , __A: Optional[int]="absolute" , __A: Optional[Any]=True , __A: Union[str, Any]=None , **__A: List[str] , ) -> Dict:
super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
_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 SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
def __A ( self: Dict ) -> Mapping[str, Mapping[int, str]]:
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),
] )
| 62 | 0 |
import argparse
import logging
import os
import datasets
import tensorflow as tf
from transformers import AutoTokenizer
__A = logging.getLogger(__name__)
def __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser(
description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' )
parser.add_argument(
'''--dataset_name''' , type=_lowercase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , )
parser.add_argument(
'''--dataset_config''' , type=_lowercase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' )
parser.add_argument(
'''--tokenizer_name_or_path''' , type=_lowercase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , )
parser.add_argument(
'''--shard_size''' , type=_lowercase , default=10_00 , help='''Number of entries to go in a single shard.''' , )
parser.add_argument('''--split''' , type=_lowercase , default='''train''' , choices=['''train''', '''test''', '''validation'''] )
parser.add_argument(
'''--limit''' , default=_lowercase , type=_lowercase , help='''Limit the number of shards (used for debugging).''' , )
parser.add_argument(
'''--max_length''' , type=_lowercase , default=5_12 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum'''
''' sequence length that is a multiple of 8.''' , )
parser.add_argument(
'''--output_dir''' , default='''tf-tpu''' , type=_lowercase , help='''Output directory where the TFRecord shards will be saved. If the'''
''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord'''
''' shards will be directly saved to a Google Cloud Storage bucket.''' , )
_A = parser.parse_args()
return args
def __A ( _lowercase ):
'''simple docstring'''
def fn(_lowercase ):
return tokenizer(examples['''text'''] )
return fn
def __A ( _lowercase ):
'''simple docstring'''
_A = []
for i in range(len(tokenized_data['''input_ids'''] ) ):
_A = {
'''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ),
'''attention_mask''': tf.train.Feature(
intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ),
}
_A = tf.train.Features(feature=_lowercase )
_A = tf.train.Example(features=_lowercase )
_A = example.SerializeToString()
records.append(_lowercase )
return records
def __A ( _lowercase ):
'''simple docstring'''
_A = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split )
if args.limit is not None:
_A = min(len(_lowercase ) , args.limit )
_A = dataset.select(range(_lowercase ) )
print(f"""Limiting the dataset to {args.limit} entries.""" )
_A = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path )
# Handle output directory creation.
# For serializing into a Google Cloud Storage Bucket, one needs to first
# create a bucket.
if "gs" not in args.output_dir:
if not os.path.exists(args.output_dir ):
os.makedirs(args.output_dir )
_A = os.path.join(args.output_dir , args.split )
if not os.path.exists(_lowercase ):
os.makedirs(_lowercase )
else:
_A = os.path.join(args.output_dir , args.split )
# Tokenize the whole dataset at once.
_A = tokenize_function(_lowercase )
_A = dataset.map(_lowercase , batched=_lowercase , num_proc=4 , remove_columns=['''text'''] )
# We need to concatenate all our texts together, and then split the result
# into chunks of a fixed size, which we will call block_size. To do this, we
# will use the map method again, with the option batched=True. When we use batched=True,
# the function we pass to map() will be passed multiple inputs at once, allowing us
# to group them into more or fewer examples than we had in the input.
# This allows us to create our new fixed-length samples. The advantage of this
# method is that we don't lose a whole lot of content from the dataset compared to the
# case where we simply tokenize with a pre-defined max_length.
def group_texts(_lowercase ):
# Concatenate all texts.
_A = {k: sum(examples[k] , [] ) for k in examples.keys()}
_A = len(concatenated_examples[list(examples.keys() )[0]] )
# We drop the small remainder, though you could add padding instead if the model supports it
# In this, as in all things, we advise you to follow your heart 🫀
_A = (total_length // args.max_length) * args.max_length
# Split by chunks of max_len.
_A = {
k: [t[i : i + args.max_length] for i in range(0 , _lowercase , args.max_length )]
for k, t in concatenated_examples.items()
}
return result
_A = dataset_tokenized.map(_lowercase , batched=_lowercase , batch_size=10_00 , num_proc=4 )
_A = 0
_A = 0
for shard in range(0 , len(_lowercase ) , args.shard_size ):
_A = grouped_dataset[shard : shard + args.shard_size]
_A = len(dataset_snapshot['''input_ids'''] )
_A = os.path.join(_lowercase , f"""dataset-{shard_count}-{records_containing}.tfrecord""" )
_A = get_serialized_examples(_lowercase )
with tf.io.TFRecordWriter(_lowercase ) as out_file:
for i in range(len(_lowercase ) ):
_A = serialized_examples[i]
out_file.write(_lowercase )
print('''Wrote file {} containing {} records'''.format(_lowercase , _lowercase ) )
shard_count += 1
total_records += records_containing
with open(f"""split-{args.split}-records-count.txt""" , '''w''' ) as f:
print(f"""Total {args.split} records: {total_records}""" , file=_lowercase )
if __name__ == "__main__":
__A = parse_args()
main(args)
| 706 |
import logging
import os
import quant_trainer
import torch
from torch.utils.data import DataLoader
from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput
__A = logging.getLogger(__name__)
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: int , *__A: str , __A: List[Any]=None , __A: Union[str, Any]=None , __A: List[Any]=None , **__A: int ) -> List[Any]:
super().__init__(*__A , **__A )
_A = eval_examples
_A = post_process_function
_A = quant_trainer_args
_A = 1_28 # default number of calibration samples
def __A ( self: Union[str, Any] , __A: List[Any]=None ) -> Optional[Any]:
if calib_dataset is None and self.calib_dataset is None:
raise ValueError('''Trainer: calibration requires an calib_dataset.''' )
_A = calib_dataset if calib_dataset is not None else self.calib_dataset
_A = self._remove_unused_columns(__A , description='''Calibration''' )
return DataLoader(
__A , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__A , )
def __A ( self: List[Any] , __A: Any=None ) -> Optional[int]:
_A = self.train_dataset if calib_dataset is None else calib_dataset
_A = self.get_calib_dataloader(__A )
_A = self.model
quant_trainer.configure_model(__A , self.quant_trainer_args , calib=__A )
model.eval()
quant_trainer.enable_calibration(__A )
logger.info('''***** Running calibration *****''' )
logger.info(f""" Num examples = {self.calib_num}""" )
logger.info(f""" Batch size = {calib_dataloader.batch_size}""" )
for step, inputs in enumerate(__A ):
# Prediction step
_A ,_A ,_A = self.prediction_step(__A , __A , prediction_loss_only=__A )
if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
break
quant_trainer.finish_calibration(__A , self.quant_trainer_args )
_A = model
def __A ( self: Any , __A: Dict=None , __A: Tuple=None , __A: List[Any]=None , __A: str = "eval" ) -> int:
_A = self.eval_dataset if eval_dataset is None else eval_dataset
_A = self.get_eval_dataloader(__A )
_A = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is not None and self.compute_metrics is not None:
_A = self.post_process_function(__A , __A , output.predictions )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
self.log(__A )
else:
_A = {}
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
_A = self.callback_handler.on_evaluate(self.args , self.state , self.control , __A )
return metrics
def __A ( self: Union[str, Any] , __A: Optional[int] , __A: int , __A: List[Any]=None , __A: str = "test" ) -> Union[str, Any]:
_A = self.get_test_dataloader(__A )
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is None or self.compute_metrics is None:
return output
_A = self.post_process_function(__A , __A , output.predictions , '''predict''' )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__A )
def __A ( self: Tuple , __A: Optional[Any]="./" ) -> List[str]:
_A = self.eval_dataset
_A = self.get_eval_dataloader(__A )
_A = next(iter(__A ) )
# saving device - to make it consistent
_A = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' )
# convert to tuple
_A = tuple(v.to(__A ) for k, v in batch.items() )
logger.info('''Converting model to be onnx compatible''' )
from pytorch_quantization.nn import TensorQuantizer
_A = True
_A = self.model.to(__A )
model.eval()
model.float()
_A = model.module if hasattr(__A , '''module''' ) else model
quant_trainer.configure_model(__A , self.quant_trainer_args )
_A = os.path.join(__A , '''model.onnx''' )
logger.info(f"""exporting model to {output_model_file}""" )
_A = {0: '''batch_size''', 1: '''seq_len'''}
torch.onnx.export(
__A , __A , __A , export_params=__A , opset_version=13 , do_constant_folding=__A , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={
'''input_ids''': axes,
'''attention_mask''': axes,
'''token_type_ids''': axes,
'''output_start_logits''': axes,
'''output_end_logits''': axes,
} , verbose=__A , )
logger.info('''onnx export finished''' )
| 62 | 0 |
import gc
import unittest
import torch
from parameterized import parameterized
from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = AutoencoderKL
A_ = "sample"
A_ = 1e-2
@property
def __A ( self: int ) -> Union[str, Any]:
_A = 4
_A = 3
_A = (32, 32)
_A = floats_tensor((batch_size, num_channels) + sizes ).to(__A )
return {"sample": image}
@property
def __A ( self: Optional[Any] ) -> List[str]:
return (3, 32, 32)
@property
def __A ( self: Tuple ) -> Optional[Any]:
return (3, 32, 32)
def __A ( self: str ) -> Any:
_A = {
'''block_out_channels''': [32, 64],
'''in_channels''': 3,
'''out_channels''': 3,
'''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],
'''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],
'''latent_channels''': 4,
}
_A = self.dummy_input
return init_dict, inputs_dict
def __A ( self: Optional[Any] ) -> Optional[Any]:
pass
def __A ( self: List[str] ) -> str:
pass
@unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' )
def __A ( self: Any ) -> Tuple:
# enable deterministic behavior for gradient checkpointing
_A ,_A = self.prepare_init_args_and_inputs_for_common()
_A = self.model_class(**__A )
model.to(__A )
assert not model.is_gradient_checkpointing and model.training
_A = model(**__A ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model.zero_grad()
_A = torch.randn_like(__A )
_A = (out - labels).mean()
loss.backward()
# re-instantiate the model now enabling gradient checkpointing
_A = self.model_class(**__A )
# clone model
model_a.load_state_dict(model.state_dict() )
model_a.to(__A )
model_a.enable_gradient_checkpointing()
assert model_a.is_gradient_checkpointing and model_a.training
_A = model_a(**__A ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model_a.zero_grad()
_A = (out_a - labels).mean()
loss_a.backward()
# compare the output and parameters gradients
self.assertTrue((loss - loss_a).abs() < 1e-5 )
_A = dict(model.named_parameters() )
_A = dict(model_a.named_parameters() )
for name, param in named_params.items():
self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) )
def __A ( self: Optional[Any] ) -> Any:
_A ,_A = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=__A )
self.assertIsNotNone(__A )
self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 )
model.to(__A )
_A = model(**self.dummy_input )
assert image is not None, "Make sure output is not None"
def __A ( self: Dict ) -> Optional[Any]:
_A = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' )
_A = model.to(__A )
model.eval()
if torch_device == "mps":
_A = torch.manual_seed(0 )
else:
_A = torch.Generator(device=__A ).manual_seed(0 )
_A = torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , )
_A = image.to(__A )
with torch.no_grad():
_A = model(__A , sample_posterior=__A , generator=__A ).sample
_A = output[0, -1, -3:, -3:].flatten().cpu()
# 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.
if torch_device == "mps":
_A = torch.tensor(
[
-4.00_78e-01,
-3.83_23e-04,
-1.26_81e-01,
-1.14_62e-01,
2.00_95e-01,
1.08_93e-01,
-8.82_47e-02,
-3.03_61e-01,
-9.86_44e-03,
] )
elif torch_device == "cpu":
_A = torch.tensor(
[-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] )
else:
_A = torch.tensor(
[-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] )
self.assertTrue(torch_all_close(__A , __A , rtol=1e-2 ) )
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Any , __A: List[Any] , __A: Optional[Any] ) -> Any:
return f"""gaussian_noise_s={seed}_shape={"_".join([str(__A ) for s in shape] )}.npy"""
def __A ( self: List[Any] ) -> List[str]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self: List[Any] , __A: Tuple=0 , __A: Any=(4, 3, 5_12, 5_12) , __A: Dict=False ) -> Union[str, Any]:
_A = torch.floataa if fpaa else torch.floataa
_A = torch.from_numpy(load_hf_numpy(self.get_file_format(__A , __A ) ) ).to(__A ).to(__A )
return image
def __A ( self: str , __A: List[str]="CompVis/stable-diffusion-v1-4" , __A: int=False ) -> str:
_A = '''fp16''' if fpaa else None
_A = torch.floataa if fpaa else torch.floataa
_A = AutoencoderKL.from_pretrained(
__A , subfolder='''vae''' , torch_dtype=__A , revision=__A , )
model.to(__A ).eval()
return model
def __A ( self: Any , __A: str=0 ) -> Tuple:
if torch_device == "mps":
return torch.manual_seed(__A )
return torch.Generator(device=__A ).manual_seed(__A )
@parameterized.expand(
[
# fmt: off
[33, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]],
[47, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]],
# fmt: on
] )
def __A ( self: Union[str, Any] , __A: Any , __A: str , __A: Any ) -> Tuple:
_A = self.get_sd_vae_model()
_A = self.get_sd_image(__A )
_A = self.get_generator(__A )
with torch.no_grad():
_A = model(__A , generator=__A , sample_posterior=__A ).sample
assert sample.shape == image.shape
_A = sample[-1, -2:, -2:, :2].flatten().float().cpu()
_A = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice )
assert torch_all_close(__A , __A , atol=3e-3 )
@parameterized.expand(
[
# fmt: off
[33, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]],
[47, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]],
# fmt: on
] )
@require_torch_gpu
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: int ) -> Tuple:
_A = self.get_sd_vae_model(fpaa=__A )
_A = self.get_sd_image(__A , fpaa=__A )
_A = self.get_generator(__A )
with torch.no_grad():
_A = model(__A , generator=__A , sample_posterior=__A ).sample
assert sample.shape == image.shape
_A = sample[-1, -2:, :2, -2:].flatten().float().cpu()
_A = torch.tensor(__A )
assert torch_all_close(__A , __A , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[33, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]],
[47, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]],
# fmt: on
] )
def __A ( self: List[str] , __A: str , __A: Tuple , __A: Optional[Any] ) -> Union[str, Any]:
_A = self.get_sd_vae_model()
_A = self.get_sd_image(__A )
with torch.no_grad():
_A = model(__A ).sample
assert sample.shape == image.shape
_A = sample[-1, -2:, -2:, :2].flatten().float().cpu()
_A = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice )
assert torch_all_close(__A , __A , atol=3e-3 )
@parameterized.expand(
[
# fmt: off
[13, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]],
[37, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]],
# fmt: on
] )
@require_torch_gpu
def __A ( self: str , __A: Tuple , __A: str ) -> str:
_A = self.get_sd_vae_model()
_A = self.get_sd_image(__A , shape=(3, 4, 64, 64) )
with torch.no_grad():
_A = model.decode(__A ).sample
assert list(sample.shape ) == [3, 3, 5_12, 5_12]
_A = sample[-1, -2:, :2, -2:].flatten().cpu()
_A = torch.tensor(__A )
assert torch_all_close(__A , __A , atol=1e-3 )
@parameterized.expand(
[
# fmt: off
[27, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]],
[16, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]],
# fmt: on
] )
@require_torch_gpu
def __A ( self: str , __A: int , __A: Optional[int] ) -> int:
_A = self.get_sd_vae_model(fpaa=__A )
_A = self.get_sd_image(__A , shape=(3, 4, 64, 64) , fpaa=__A )
with torch.no_grad():
_A = model.decode(__A ).sample
assert list(sample.shape ) == [3, 3, 5_12, 5_12]
_A = sample[-1, -2:, :2, -2:].flatten().float().cpu()
_A = torch.tensor(__A )
assert torch_all_close(__A , __A , atol=5e-3 )
@parameterized.expand([(13,), (16,), (27,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' )
def __A ( self: Any , __A: Dict ) -> Union[str, Any]:
_A = self.get_sd_vae_model(fpaa=__A )
_A = self.get_sd_image(__A , shape=(3, 4, 64, 64) , fpaa=__A )
with torch.no_grad():
_A = model.decode(__A ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
_A = model.decode(__A ).sample
assert list(sample.shape ) == [3, 3, 5_12, 5_12]
assert torch_all_close(__A , __A , atol=1e-1 )
@parameterized.expand([(13,), (16,), (37,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' )
def __A ( self: Any , __A: Tuple ) -> Optional[Any]:
_A = self.get_sd_vae_model()
_A = self.get_sd_image(__A , shape=(3, 4, 64, 64) )
with torch.no_grad():
_A = model.decode(__A ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
_A = model.decode(__A ).sample
assert list(sample.shape ) == [3, 3, 5_12, 5_12]
assert torch_all_close(__A , __A , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[33, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]],
[47, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]],
# fmt: on
] )
def __A ( self: str , __A: Dict , __A: Any ) -> Tuple:
_A = self.get_sd_vae_model()
_A = self.get_sd_image(__A )
_A = self.get_generator(__A )
with torch.no_grad():
_A = model.encode(__A ).latent_dist
_A = dist.sample(generator=__A )
assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
_A = sample[0, -1, -3:, -3:].flatten().cpu()
_A = torch.tensor(__A )
_A = 3e-3 if torch_device != '''mps''' else 1e-2
assert torch_all_close(__A , __A , atol=__A )
| 707 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__A = {
'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MegaForCausalLM',
'MegaForMaskedLM',
'MegaForMultipleChoice',
'MegaForQuestionAnswering',
'MegaForSequenceClassification',
'MegaForTokenClassification',
'MegaModel',
'MegaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 62 | 0 |
from __future__ import annotations
import unittest
from transformers import LEDConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFLEDForConditionalGeneration, TFLEDModel
@require_tf
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
A_ = LEDConfig
A_ = {}
A_ = "gelu"
def __init__( self: Union[str, Any] , __A: Dict , __A: Optional[Any]=13 , __A: Optional[int]=7 , __A: str=True , __A: Union[str, Any]=False , __A: List[Any]=99 , __A: Tuple=32 , __A: str=2 , __A: Optional[Any]=4 , __A: Optional[int]=37 , __A: str=0.1 , __A: Tuple=0.1 , __A: List[Any]=20 , __A: Optional[Any]=2 , __A: Union[str, Any]=1 , __A: Optional[int]=0 , __A: Optional[Any]=4 , ) -> List[Any]:
_A = parent
_A = batch_size
_A = seq_length
_A = is_training
_A = use_labels
_A = vocab_size
_A = hidden_size
_A = num_hidden_layers
_A = num_attention_heads
_A = intermediate_size
_A = hidden_dropout_prob
_A = attention_probs_dropout_prob
_A = max_position_embeddings
_A = eos_token_id
_A = pad_token_id
_A = bos_token_id
_A = attention_window
# `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size
# [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention
# returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1]
# because its local attention only attends to `self.attention_window` and one before and one after
_A = self.attention_window + 2
# because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for
# the `test_attention_outputs` and `test_hidden_states_output` tests
_A = (
self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window
)
def __A ( self: Dict ) -> Any:
_A = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
_A = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
_A = tf.concat([input_ids, eos_tensor] , axis=1 )
_A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_A = 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 , attention_window=self.attention_window , **self.config_updates , )
_A = prepare_led_inputs_dict(__A , __A , __A )
_A = tf.concat(
[tf.zeros_like(__A )[:, :-1], tf.ones_like(__A )[:, -1:]] , axis=-1 , )
_A = global_attention_mask
return config, inputs_dict
def __A ( self: int , __A: Dict , __A: Optional[int] ) -> List[Any]:
_A = TFLEDModel(config=__A ).get_decoder()
_A = inputs_dict['''input_ids''']
_A = input_ids[:1, :]
_A = inputs_dict['''attention_mask'''][:1, :]
_A = 1
# first forward pass
_A = model(__A , attention_mask=__A , use_cache=__A )
_A ,_A = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
_A = ids_tensor((self.batch_size, 3) , config.vocab_size )
_A = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
_A = tf.concat([input_ids, next_tokens] , axis=-1 )
_A = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
_A = model(__A , attention_mask=__A )[0]
_A = model(__A , attention_mask=__A , past_key_values=__A )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
_A = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
_A = output_from_no_past[:, -3:, random_slice_idx]
_A = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(__A , __A , rtol=1e-3 )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , ):
'''simple docstring'''
if attention_mask is None:
_A = tf.cast(tf.math.not_equal(_lowercase , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
_A = 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:
_A = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_A = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"decoder_input_ids": decoder_input_ids,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
}
@require_tf
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else ()
A_ = (TFLEDForConditionalGeneration,) if is_tf_available() else ()
A_ = (
{
"conversational": TFLEDForConditionalGeneration,
"feature-extraction": TFLEDModel,
"summarization": TFLEDForConditionalGeneration,
"text2text-generation": TFLEDForConditionalGeneration,
"translation": TFLEDForConditionalGeneration,
}
if is_tf_available()
else {}
)
A_ = True
A_ = False
A_ = False
A_ = False
def __A ( self: Any ) -> List[Any]:
_A = TFLEDModelTester(self )
_A = ConfigTester(self , config_class=__A )
def __A ( self: int ) -> Union[str, Any]:
self.config_tester.run_common_tests()
def __A ( self: List[str] ) -> int:
_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__A )
def __A ( self: Optional[int] ) -> Optional[int]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
_A = tf.zeros_like(inputs_dict['''attention_mask'''] )
_A = 2
_A = tf.where(
tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['''global_attention_mask'''] , )
_A = True
_A = self.model_tester.seq_length
_A = self.model_tester.encoder_seq_length
def check_decoder_attentions_output(__A: str ):
_A = outputs.decoder_attentions
self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , )
def check_encoder_attentions_output(__A: Tuple ):
_A = [t.numpy() for t in outputs.encoder_attentions]
_A = [t.numpy() for t in outputs.encoder_global_attentions]
self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers )
self.assertEqual(len(__A ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , )
self.assertListEqual(
list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , )
for model_class in self.all_model_classes:
_A = True
_A = False
_A = False
_A = model_class(__A )
_A = model(self._prepare_for_class(__A , __A ) )
_A = len(__A )
self.assertEqual(config.output_hidden_states , __A )
check_encoder_attentions_output(__A )
if self.is_encoder_decoder:
_A = model_class(__A )
_A = model(self._prepare_for_class(__A , __A ) )
self.assertEqual(config.output_hidden_states , __A )
check_decoder_attentions_output(__A )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
_A = True
_A = model_class(__A )
_A = model(self._prepare_for_class(__A , __A ) )
self.assertEqual(config.output_hidden_states , __A )
check_encoder_attentions_output(__A )
# Check attention is always last and order is fine
_A = True
_A = True
_A = model_class(__A )
_A = model(self._prepare_for_class(__A , __A ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__A ) )
self.assertEqual(model.config.output_hidden_states , __A )
check_encoder_attentions_output(__A )
@unittest.skip('''LED keeps using potentially symbolic tensors in conditionals and breaks tracing.''' )
def __A ( self: Optional[int] ) -> List[str]:
pass
def __A ( self: Dict ) -> Optional[Any]:
# TODO: Head-masking not yet implement
pass
def __A ( _lowercase ):
'''simple docstring'''
return tf.constant(_lowercase , dtype=tf.intaa )
__A = 1e-4
@slow
@require_tf
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Optional[int] ) -> Any:
_A = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' ).led
# change to intended input here
_A = _long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
_A = _long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
_A = prepare_led_inputs_dict(model.config , __A , __A )
_A = model(**__A )[0]
_A = (1, 10_24, 7_68)
self.assertEqual(output.shape , __A )
# change to expected output here
_A = tf.convert_to_tensor(
[[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]] , )
tf.debugging.assert_near(output[:, :3, :3] , __A , atol=1e-3 )
def __A ( self: Any ) -> Union[str, Any]:
_A = TFLEDForConditionalGeneration.from_pretrained('''allenai/led-base-16384''' )
# change to intended input here
_A = _long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
_A = _long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
_A = prepare_led_inputs_dict(model.config , __A , __A )
_A = model(**__A )[0]
_A = (1, 10_24, model.config.vocab_size)
self.assertEqual(output.shape , __A )
# change to expected output here
_A = tf.convert_to_tensor(
[[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]] , )
tf.debugging.assert_near(output[:, :3, :3] , __A , atol=1e-3 , rtol=1e-3 )
| 708 |
import itertools
import string
from collections.abc import Generator, Iterable
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = iter(_lowercase )
while True:
_A = tuple(itertools.islice(_lowercase , _lowercase ) )
if not chunk:
return
yield chunk
def __A ( _lowercase ):
'''simple docstring'''
_A = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] )
_A = ''''''
if len(_lowercase ) < 2:
return dirty
for i in range(len(_lowercase ) - 1 ):
clean += dirty[i]
if dirty[i] == dirty[i + 1]:
clean += "X"
clean += dirty[-1]
if len(_lowercase ) & 1:
clean += "X"
return clean
def __A ( _lowercase ):
'''simple docstring'''
_A = '''ABCDEFGHIKLMNOPQRSTUVWXYZ'''
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
_A = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(_lowercase )
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(_lowercase )
return table
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = prepare_input(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
ciphertext += table[rowa * 5 + (cola + 1) % 5]
ciphertext += table[rowa * 5 + (cola + 1) % 5]
elif cola == cola:
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
else: # rectangle
ciphertext += table[rowa * 5 + cola]
ciphertext += table[rowa * 5 + cola]
return ciphertext
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
plaintext += table[rowa * 5 + (cola - 1) % 5]
plaintext += table[rowa * 5 + (cola - 1) % 5]
elif cola == cola:
plaintext += table[((rowa - 1) % 5) * 5 + cola]
plaintext += table[((rowa - 1) % 5) * 5 + cola]
else: # rectangle
plaintext += table[rowa * 5 + cola]
plaintext += table[rowa * 5 + cola]
return plaintext
| 62 | 0 |
import os
import socket
from contextlib import contextmanager
import torch
from ..commands.config.default import write_basic_config # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version
if is_deepspeed_available():
from deepspeed import DeepSpeedEngine
if is_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
def __A ( _lowercase : Tuple ):
'''simple docstring'''
if is_torch_version('''<''' , '''2.0.0''' ) or not hasattr(_lowercase , '''_dynamo''' ):
return False
return isinstance(_lowercase , torch._dynamo.eval_frame.OptimizedModule )
def __A ( _lowercase : Union[str, Any] , _lowercase : int = True ):
'''simple docstring'''
_A = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)
_A = is_compiled_module(_lowercase )
if is_compiled:
_A = model
_A = model._orig_mod
if is_deepspeed_available():
options += (DeepSpeedEngine,)
while isinstance(_lowercase , _lowercase ):
_A = model.module
if not keep_fpaa_wrapper:
_A = getattr(_lowercase , '''forward''' )
_A = model.__dict__.pop('''_original_forward''' , _lowercase )
if original_forward is not None:
while hasattr(_lowercase , '''__wrapped__''' ):
_A = forward.__wrapped__
if forward == original_forward:
break
_A = forward
if getattr(_lowercase , '''_converted_to_transformer_engine''' , _lowercase ):
convert_model(_lowercase , to_transformer_engine=_lowercase )
if is_compiled:
_A = model
_A = compiled_model
return model
def __A ( ):
'''simple docstring'''
PartialState().wait_for_everyone()
def __A ( _lowercase : Tuple , _lowercase : List[Any] ):
'''simple docstring'''
if PartialState().distributed_type == DistributedType.TPU:
xm.save(_lowercase , _lowercase )
elif PartialState().local_process_index == 0:
torch.save(_lowercase , _lowercase )
@contextmanager
def __A ( **_lowercase : List[Any] ):
'''simple docstring'''
for key, value in kwargs.items():
_A = str(_lowercase )
yield
for key in kwargs:
if key.upper() in os.environ:
del os.environ[key.upper()]
def __A ( _lowercase : int ):
'''simple docstring'''
if not hasattr(_lowercase , '''__qualname__''' ) and not hasattr(_lowercase , '''__name__''' ):
_A = getattr(_lowercase , '''__class__''' , _lowercase )
if hasattr(_lowercase , '''__qualname__''' ):
return obj.__qualname__
if hasattr(_lowercase , '''__name__''' ):
return obj.__name__
return str(_lowercase )
def __A ( _lowercase : str , _lowercase : List[Any] ):
'''simple docstring'''
for key, value in source.items():
if isinstance(_lowercase , _lowercase ):
_A = destination.setdefault(_lowercase , {} )
merge_dicts(_lowercase , _lowercase )
else:
_A = value
return destination
def __A ( _lowercase : Union[str, Any] = None ):
'''simple docstring'''
if port is None:
_A = 2_95_00
with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s:
return s.connect_ex(('''localhost''', port) ) == 0
| 709 |
import gc
import unittest
from transformers import CTRLConfig, 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, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Tuple , __A: Any , __A: List[Any]=14 , __A: Dict=7 , __A: List[str]=True , __A: Tuple=True , __A: Union[str, Any]=True , __A: List[Any]=True , __A: Optional[int]=True , __A: Tuple=99 , __A: Optional[Any]=32 , __A: List[str]=5 , __A: Dict=4 , __A: str=37 , __A: Dict="gelu" , __A: List[str]=0.1 , __A: str=0.1 , __A: Any=5_12 , __A: Union[str, Any]=16 , __A: List[Any]=2 , __A: Tuple=0.02 , __A: Tuple=3 , __A: Union[str, Any]=4 , __A: Any=None , ) -> Optional[Any]:
_A = parent
_A = batch_size
_A = seq_length
_A = is_training
_A = use_token_type_ids
_A = use_input_mask
_A = use_labels
_A = use_mc_token_ids
_A = vocab_size
_A = hidden_size
_A = num_hidden_layers
_A = num_attention_heads
_A = intermediate_size
_A = hidden_act
_A = hidden_dropout_prob
_A = attention_probs_dropout_prob
_A = max_position_embeddings
_A = type_vocab_size
_A = type_sequence_label_size
_A = initializer_range
_A = num_labels
_A = num_choices
_A = scope
_A = self.vocab_size - 1
def __A ( self: Optional[int] ) -> Union[str, Any]:
_A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_A = None
if self.use_input_mask:
_A = random_attention_mask([self.batch_size, self.seq_length] )
_A = None
if self.use_token_type_ids:
_A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_A = None
if self.use_mc_token_ids:
_A = ids_tensor([self.batch_size, self.num_choices] , self.seq_length )
_A = None
_A = None
_A = None
if self.use_labels:
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_A = ids_tensor([self.batch_size] , self.num_choices )
_A = self.get_config()
_A = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
token_type_ids,
mc_token_ids,
sequence_labels,
token_labels,
choice_labels,
)
def __A ( self: Optional[int] ) -> List[Any]:
return CTRLConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , )
def __A ( self: Union[str, Any] , __A: Union[str, Any] , __A: Dict , __A: Optional[int] , __A: List[str] , __A: List[str] , *__A: Optional[int] ) -> Optional[Any]:
_A = CTRLModel(config=__A )
model.to(__A )
model.eval()
model(__A , token_type_ids=__A , head_mask=__A )
model(__A , token_type_ids=__A )
_A = model(__A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(len(result.past_key_values ) , config.n_layer )
def __A ( self: Optional[Any] , __A: List[str] , __A: Dict , __A: List[Any] , __A: List[Any] , __A: Any , *__A: Any ) -> str:
_A = CTRLLMHeadModel(__A )
model.to(__A )
model.eval()
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __A ( self: Optional[int] ) -> Dict:
_A = self.prepare_config_and_inputs()
(
(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,
) = config_and_inputs
_A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}
return config, inputs_dict
def __A ( self: List[str] , __A: Dict , __A: Dict , __A: Tuple , __A: List[Any] , *__A: Optional[int] ) -> Any:
_A = self.num_labels
_A = CTRLForSequenceClassification(__A )
model.to(__A )
model.eval()
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
A_ = (CTRLLMHeadModel,) if is_torch_available() else ()
A_ = (
{
"feature-extraction": CTRLModel,
"text-classification": CTRLForSequenceClassification,
"text-generation": CTRLLMHeadModel,
"zero-shot": CTRLForSequenceClassification,
}
if is_torch_available()
else {}
)
A_ = True
A_ = False
A_ = False
def __A ( self: Any , __A: List[Any] , __A: int , __A: Optional[Any] , __A: Optional[int] , __A: List[Any] ) -> List[str]:
if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
# config could not be created.
return True
return False
def __A ( self: Any ) -> Union[str, Any]:
_A = CTRLModelTester(self )
_A = ConfigTester(self , config_class=__A , n_embd=37 )
def __A ( self: Optional[int] ) -> List[Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
def __A ( self: Dict ) -> Any:
self.config_tester.run_common_tests()
def __A ( self: str ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_ctrl_model(*__A )
def __A ( self: List[str] ) -> Any:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head_model(*__A )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: Optional[Any] ) -> int:
pass
@slow
def __A ( self: Tuple ) -> Dict:
for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_A = CTRLModel.from_pretrained(__A )
self.assertIsNotNone(__A )
@unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :)
def __A ( self: Any ) -> Union[str, Any]:
pass
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: int ) -> Union[str, Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
@slow
def __A ( self: Any ) -> Any:
_A = CTRLLMHeadModel.from_pretrained('''ctrl''' )
model.to(__A )
_A = torch.tensor(
[[1_18_59, 0, 16_11, 8]] , dtype=torch.long , device=__A ) # Legal the president is
_A = [
1_18_59,
0,
16_11,
8,
5,
1_50,
2_64_49,
2,
19,
3_48,
4_69,
3,
25_95,
48,
2_07_40,
24_65_33,
24_65_33,
19,
30,
5,
] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a
_A = model.generate(__A , do_sample=__A )
self.assertListEqual(output_ids[0].tolist() , __A )
| 62 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json',
'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json',
'xlm-roberta-large-finetuned-conll02-dutch': (
'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json'
),
'xlm-roberta-large-finetuned-conll02-spanish': (
'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json'
),
'xlm-roberta-large-finetuned-conll03-english': (
'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json'
),
'xlm-roberta-large-finetuned-conll03-german': (
'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json'
),
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "xlm-roberta"
def __init__( self: List[Any] , __A: List[str]=3_05_22 , __A: Optional[Any]=7_68 , __A: str=12 , __A: Dict=12 , __A: int=30_72 , __A: Union[str, Any]="gelu" , __A: Tuple=0.1 , __A: Dict=0.1 , __A: List[Any]=5_12 , __A: int=2 , __A: Any=0.02 , __A: Optional[int]=1e-12 , __A: Union[str, Any]=1 , __A: Dict=0 , __A: Optional[Any]=2 , __A: Dict="absolute" , __A: List[str]=True , __A: List[str]=None , **__A: Any , ) -> Dict:
super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
_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 SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
def __A ( self: Union[str, Any] ) -> Mapping[str, Mapping[int, str]]:
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),
] )
| 710 |
__A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
__A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = []
for neighbour in graph[vert]:
if not visited[neighbour]:
order += topology_sort(_lowercase , _lowercase , _lowercase )
order.append(_lowercase )
return order
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = [vert]
for neighbour in reversed_graph[vert]:
if not visited[neighbour]:
component += find_components(_lowercase , _lowercase , _lowercase )
return component
def __A ( _lowercase ):
'''simple docstring'''
_A = len(_lowercase ) * [False]
_A = {vert: [] for vert in range(len(_lowercase ) )}
for vert, neighbours in graph.items():
for neighbour in neighbours:
reversed_graph[neighbour].append(_lowercase )
_A = []
for i, was_visited in enumerate(_lowercase ):
if not was_visited:
order += topology_sort(_lowercase , _lowercase , _lowercase )
_A = []
_A = len(_lowercase ) * [False]
for i in range(len(_lowercase ) ):
_A = order[len(_lowercase ) - i - 1]
if not visited[vert]:
_A = find_components(_lowercase , _lowercase , _lowercase )
components_list.append(_lowercase )
return components_list
| 62 | 0 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Optional[int] , __A: Optional[Any] ) -> str:
_A = question_encoder
_A = generator
_A = self.question_encoder
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Dict:
if os.path.isfile(__A ):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(__A , exist_ok=__A )
_A = os.path.join(__A , '''question_encoder_tokenizer''' )
_A = os.path.join(__A , '''generator_tokenizer''' )
self.question_encoder.save_pretrained(__A )
self.generator.save_pretrained(__A )
@classmethod
def __A ( cls: Optional[Any] , __A: List[str] , **__A: int ) -> Any:
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
_A = kwargs.pop('''config''' , __A )
if config is None:
_A = RagConfig.from_pretrained(__A )
_A = AutoTokenizer.from_pretrained(
__A , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' )
_A = AutoTokenizer.from_pretrained(
__A , config=config.generator , subfolder='''generator_tokenizer''' )
return cls(question_encoder=__A , generator=__A )
def __call__( self: int , *__A: Optional[int] , **__A: List[str] ) -> int:
return self.current_tokenizer(*__A , **__A )
def __A ( self: Dict , *__A: List[str] , **__A: List[str] ) -> Dict:
return self.generator.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Tuple , **__A: List[str] ) -> Tuple:
return self.generator.decode(*__A , **__A )
def __A ( self: Dict ) -> List[str]:
_A = self.question_encoder
def __A ( self: Union[str, Any] ) -> int:
_A = self.generator
def __A ( self: Dict , __A: List[str] , __A: Optional[List[str]] = None , __A: Optional[int] = None , __A: Optional[int] = None , __A: str = "longest" , __A: str = None , __A: bool = True , **__A: Tuple , ) -> BatchEncoding:
warnings.warn(
'''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
'''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
'''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
'''details''' , __A , )
if max_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
__A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , )
_A = labels['''input_ids''']
return model_inputs
| 711 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
global f # a global dp table for knapsack
if f[i][j] < 0:
if j < wt[i - 1]:
_A = mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase )
else:
_A = max(
mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase ) , mf_knapsack(i - 1 , _lowercase , _lowercase , j - wt[i - 1] ) + val[i - 1] , )
_A = val
return f[i][j]
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = [[0] * (w + 1) for _ in range(n + 1 )]
for i in range(1 , n + 1 ):
for w_ in range(1 , w + 1 ):
if wt[i - 1] <= w_:
_A = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] )
else:
_A = dp[i - 1][w_]
return dp[n][w_], dp
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if not (isinstance(_lowercase , (list, tuple) ) and isinstance(_lowercase , (list, tuple) )):
raise ValueError(
'''Both the weights and values vectors must be either lists or tuples''' )
_A = len(_lowercase )
if num_items != len(_lowercase ):
_A = (
'''The number of weights must be the same as the number of values.\n'''
f"""But got {num_items} weights and {len(_lowercase )} values"""
)
raise ValueError(_lowercase )
for i in range(_lowercase ):
if not isinstance(wt[i] , _lowercase ):
_A = (
'''All weights must be integers but got weight of '''
f"""type {type(wt[i] )} at index {i}"""
)
raise TypeError(_lowercase )
_A ,_A = knapsack(_lowercase , _lowercase , _lowercase , _lowercase )
_A = set()
_construct_solution(_lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
return optimal_val, example_optional_set
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if i > 0 and j > 0:
if dp[i - 1][j] == dp[i][j]:
_construct_solution(_lowercase , _lowercase , i - 1 , _lowercase , _lowercase )
else:
optimal_set.add(_lowercase )
_construct_solution(_lowercase , _lowercase , i - 1 , j - wt[i - 1] , _lowercase )
if __name__ == "__main__":
__A = [3, 2, 4, 4]
__A = [4, 3, 2, 3]
__A = 4
__A = 6
__A = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)]
__A , __A = knapsack(w, wt, val, n)
print(optimal_solution)
print(mf_knapsack(n, wt, val, w)) # switched the n and w
# testing the dynamic programming problem with example
# the optimal subset for the above example are items 3 and 4
__A , __A = knapsack_with_example_solution(w, wt, val)
assert optimal_solution == 8
assert optimal_subset == {3, 4}
print('optimal_value = ', optimal_solution)
print('An optimal subset corresponding to the optimal value', optimal_subset)
| 62 | 0 |
import unittest
import numpy as np
from transformers.testing_utils import require_pytesseract, require_torch
from transformers.utils import is_pytesseract_available, is_torch_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_pytesseract_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __init__( self: Optional[int] , __A: Optional[int] , __A: Optional[Any]=7 , __A: Any=3 , __A: Dict=18 , __A: List[Any]=30 , __A: Union[str, Any]=4_00 , __A: Tuple=True , __A: Dict=None , __A: Optional[int]=True , ) -> Optional[int]:
_A = size if size is not None else {'''height''': 18, '''width''': 18}
_A = parent
_A = batch_size
_A = num_channels
_A = image_size
_A = min_resolution
_A = max_resolution
_A = do_resize
_A = size
_A = apply_ocr
def __A ( self: List[Any] ) -> Optional[Any]:
return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr}
@require_torch
@require_pytesseract
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None
def __A ( self: Any ) -> Optional[int]:
_A = LayoutLMvaImageProcessingTester(self )
@property
def __A ( self: Optional[int] ) -> List[str]:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self: Optional[Any] ) -> List[str]:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , '''do_resize''' ) )
self.assertTrue(hasattr(__A , '''size''' ) )
self.assertTrue(hasattr(__A , '''apply_ocr''' ) )
def __A ( self: Optional[int] ) -> Optional[int]:
_A = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} )
_A = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} )
def __A ( self: List[str] ) -> Union[str, Any]:
pass
def __A ( self: Optional[Any] ) -> Tuple:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' )
self.assertEqual(
encoding.pixel_values.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
self.assertIsInstance(encoding.words , __A )
self.assertIsInstance(encoding.boxes , __A )
# Test batched
_A = image_processing(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
def __A ( self: Optional[int] ) -> str:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A )
for image in image_inputs:
self.assertIsInstance(__A , np.ndarray )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_A = image_processing(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
def __A ( self: Optional[Any] ) -> int:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A )
for image in image_inputs:
self.assertIsInstance(__A , torch.Tensor )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
# Test batched
_A = image_processing(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['''height'''],
self.image_processor_tester.size['''width'''],
) , )
def __A ( self: str ) -> Optional[Any]:
# with apply_OCR = True
_A = LayoutLMvaImageProcessor()
from datasets import load_dataset
_A = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' )
_A = Image.open(ds[0]['''file'''] ).convert('''RGB''' )
_A = image_processing(__A , return_tensors='''pt''' )
self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
self.assertEqual(len(encoding.words ) , len(encoding.boxes ) )
# fmt: off
# the words and boxes were obtained with Tesseract 4.1.1
_A = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231
_A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231
# fmt: on
self.assertListEqual(encoding.words , __A )
self.assertListEqual(encoding.boxes , __A )
# with apply_OCR = False
_A = LayoutLMvaImageProcessor(apply_ocr=__A )
_A = image_processing(__A , return_tensors='''pt''' )
self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
| 712 |
def __A ( _lowercase = 1_00_00_00 ):
'''simple docstring'''
_A = 1
_A = 1
_A = {1: 1}
for inputa in range(2 , _lowercase ):
_A = 0
_A = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_A = (3 * number) + 1
counter += 1
if inputa not in counters:
_A = counter
if counter > pre_counter:
_A = inputa
_A = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {
'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:
__A = [
'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
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 713 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = word.split()
def justify(_lowercase , _lowercase , _lowercase ) -> str:
_A = max_width - width
_A = len(_lowercase )
if len(_lowercase ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_A = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_A = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_A = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_lowercase ):
num_spaces_between_words_list[i] += 1
_A = []
for i in range(_lowercase ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * ''' ''' )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_lowercase )
_A = []
_A = []
_A = 0
for word in words:
if width + len(_lowercase ) + len(_lowercase ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_lowercase )
width += len(_lowercase )
else:
# justify the line and add it to result
answer.append(justify(_lowercase , _lowercase , _lowercase ) )
# reset new line and new width
_A ,_A = [word], len(_lowercase )
_A = max_width - width - len(_lowercase )
answer.append(''' '''.join(_lowercase ) + (remaining_spaces + 1) * ''' ''' )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 62 | 0 |
import copy
from typing import Dict, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
from ..detr import DetrConfig
from ..swin import SwinConfig
__A = {
'facebook/maskformer-swin-base-ade': (
'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json'
)
# See all MaskFormer models at https://huggingface.co/models?filter=maskformer
}
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "maskformer"
A_ = {"hidden_size": "mask_feature_size"}
A_ = ["resnet", "swin"]
A_ = ["detr"]
def __init__( self: int , __A: int = 2_56 , __A: int = 2_56 , __A: float = 0.1 , __A: bool = False , __A: Optional[Dict] = None , __A: Optional[Dict] = None , __A: float = 0.02 , __A: float = 1.0 , __A: float = 1.0 , __A: float = 1.0 , __A: float = 20.0 , __A: Optional[bool] = None , **__A: Optional[Any] , ) -> List[Any]:
if backbone_config is None:
# fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k
_A = SwinConfig(
image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , )
if isinstance(__A , __A ):
_A = backbone_config.pop('''model_type''' )
_A = CONFIG_MAPPING[backbone_model_type]
_A = config_class.from_dict(__A )
# verify that the backbone is supported
if backbone_config.model_type not in self.backbones_supported:
logger.warning_once(
f"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. """
f"""Supported model types: {",".join(self.backbones_supported )}""" )
if decoder_config is None:
# fall back to https://huggingface.co/facebook/detr-resnet-50
_A = DetrConfig()
else:
# verify that the decoder is supported
_A = (
decoder_config.pop('''model_type''' ) if isinstance(__A , __A ) else decoder_config.model_type
)
if decoder_type not in self.decoders_supported:
raise ValueError(
f"""Transformer Decoder {decoder_type} not supported, please use one of"""
f""" {",".join(self.decoders_supported )}""" )
if isinstance(__A , __A ):
_A = CONFIG_MAPPING[decoder_type]
_A = config_class.from_dict(__A )
_A = backbone_config
_A = decoder_config
# main feature dimension for the model
_A = fpn_feature_size
_A = mask_feature_size
# initializer
_A = init_std
_A = init_xavier_std
# Hungarian matcher && loss
_A = cross_entropy_weight
_A = dice_weight
_A = mask_weight
_A = use_auxiliary_loss
_A = no_object_weight
_A = output_auxiliary_logits
_A = self.decoder_config.encoder_attention_heads
_A = self.decoder_config.num_hidden_layers
super().__init__(**__A )
@classmethod
def __A ( cls: Dict , __A: PretrainedConfig , __A: PretrainedConfig , **__A: Any ) -> int:
return cls(
backbone_config=__A , decoder_config=__A , **__A , )
def __A ( self: int ) -> Dict[str, any]:
_A = copy.deepcopy(self.__dict__ )
_A = self.backbone_config.to_dict()
_A = self.decoder_config.to_dict()
_A = self.__class__.model_type
return output
| 714 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(_lowercase , '''utf-8''' )
with zstd.open(_lowercase , '''wb''' ) as f:
f.write(_lowercase )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , _lowercase ) , '''w''' ) as f:
f.write(_lowercase )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=_lowercase , extract_compressed_file=_lowercase )
_A = cached_path(_lowercase , download_config=_lowercase )
with open(_lowercase ) as f:
_A = f.read()
with open(_lowercase ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , _lowercase )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(_lowercase ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=_lowercase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowercase )
)
_A = cached_path(_lowercase , download_config=_lowercase )
assert Path(_lowercase ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(_lowercase ).resolve() )
assert cached_path(_lowercase ) == text_file
# relative path
_A = str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowercase ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(_lowercase ):
cached_path(_lowercase )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(_lowercase ):
cached_path(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(_lowercase ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( ):
'''simple docstring'''
with pytest.raises(_lowercase ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
http_get('''https://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
ftp_get('''ftp://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
fsspec_get('''s3://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
fsspec_head('''s3://huggingface.co''' )
| 62 | 0 |
'''simple docstring'''
def __A ( _lowercase ):
'''simple docstring'''
if bit_count < 0:
raise ValueError('''The given input must be positive''' )
# get the generated string sequence
_A = gray_code_sequence_string(_lowercase )
#
# convert them to integers
for i in range(len(_lowercase ) ):
_A = int(sequence[i] , 2 )
return sequence
def __A ( _lowercase ):
'''simple docstring'''
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
_A = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
_A = gray_code_sequence_string(bit_count - 1 )
_A = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2 ):
_A = '''0''' + smaller_sequence[i]
sequence.append(_lowercase )
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2 ) ):
_A = '''1''' + smaller_sequence[i]
sequence.append(_lowercase )
return sequence
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 |
import os
from tempfile import TemporaryDirectory
from unittest import TestCase
import pytest
from absl.testing import parameterized
from datasets import config
from datasets.arrow_reader import HF_GCP_BASE_URL
from datasets.builder import DatasetBuilder
from datasets.dataset_dict import IterableDatasetDict
from datasets.iterable_dataset import IterableDataset
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.file_utils import cached_path
__A = [
{'dataset': 'wikipedia', 'config_name': '20220301.de'},
{'dataset': 'wikipedia', 'config_name': '20220301.en'},
{'dataset': 'wikipedia', 'config_name': '20220301.fr'},
{'dataset': 'wikipedia', 'config_name': '20220301.frr'},
{'dataset': 'wikipedia', 'config_name': '20220301.it'},
{'dataset': 'wikipedia', 'config_name': '20220301.simple'},
{'dataset': 'snli', 'config_name': 'plain_text'},
{'dataset': 'eli5', 'config_name': 'LFQA_reddit'},
{'dataset': 'wiki40b', 'config_name': 'en'},
{'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'},
{'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'},
{'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'},
{'dataset': 'natural_questions', 'config_name': 'default'},
]
def __A ( _lowercase=True ):
'''simple docstring'''
if with_config:
return [
{
"testcase_name": d["dataset"] + "/" + d["config_name"],
"dataset": d["dataset"],
"config_name": d["config_name"],
}
for d in DATASETS_ON_HF_GCP
]
else:
return [
{"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP}
]
@parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=snake_case ) )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = None
A_ = None
def __A ( self: Union[str, Any] , __A: Dict , __A: Any ) -> Any:
with TemporaryDirectory() as tmp_dir:
_A = dataset_module_factory(__A , cache_dir=__A )
_A = import_main_class(dataset_module.module_path , dataset=__A )
_A = builder_cls(
cache_dir=__A , config_name=__A , hash=dataset_module.hash , )
_A = '''/'''.join(
[
HF_GCP_BASE_URL,
builder_instance._relative_data_dir(with_hash=__A ).replace(os.sep , '''/''' ),
config.DATASET_INFO_FILENAME,
] )
_A = cached_path(__A , cache_dir=__A )
self.assertTrue(os.path.exists(__A ) )
@pytest.mark.integration
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''test_hf_gcp''' ) / '''test_wikipedia_simple'''
_A = dataset_module_factory('''wikipedia''' , cache_dir=_lowercase )
_A = import_main_class(dataset_module.module_path )
_A = builder_cls(
cache_dir=_lowercase , config_name='''20220301.frr''' , hash=dataset_module.hash , )
# use the HF cloud storage, not the original download_and_prepare that uses apache-beam
_A = None
builder_instance.download_and_prepare()
_A = builder_instance.as_dataset()
assert ds
@pytest.mark.integration
def __A ( _lowercase ):
'''simple docstring'''
_A = dataset_module_factory('''wikipedia''' , cache_dir=_lowercase )
_A = import_main_class(dataset_module.module_path , dataset=_lowercase )
_A = builder_cls(
cache_dir=_lowercase , config_name='''20220301.frr''' , hash=dataset_module.hash , )
_A = builder_instance.as_streaming_dataset()
assert ds
assert isinstance(_lowercase , _lowercase )
assert "train" in ds
assert isinstance(ds['''train'''] , _lowercase )
assert next(iter(ds['''train'''] ) )
| 716 |
import flax.linen as nn
import jax
import jax.numpy as jnp
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: Tuple ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Dict , __A: Dict ) -> Tuple:
_A ,_A ,_A ,_A = hidden_states.shape
_A = jax.image.resize(
__A , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , )
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: List[str] ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Union[str, Any] , __A: List[Any] ) -> Union[str, Any]:
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = None
A_ = 0.0
A_ = None
A_ = jnp.floataa
def __A ( self: Dict ) -> Dict:
_A = self.in_channels if self.out_channels is None else self.out_channels
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = nn.Dense(__A , dtype=self.dtype )
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Dropout(self.dropout_prob )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
_A = None
if use_nin_shortcut:
_A = nn.Conv(
__A , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , )
def __call__( self: Dict , __A: List[Any] , __A: List[Any] , __A: Any=True ) -> List[Any]:
_A = hidden_states
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.conva(__A )
_A = self.time_emb_proj(nn.swish(__A ) )
_A = jnp.expand_dims(jnp.expand_dims(__A , 1 ) , 1 )
_A = hidden_states + temb
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.dropout(__A , __A )
_A = self.conva(__A )
if self.conv_shortcut is not None:
_A = self.conv_shortcut(__A )
return hidden_states + residual
| 62 | 0 |
from __future__ import annotations
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
if len(_lowercase ) <= 1 or n <= 1:
return
insert_next(_lowercase , n - 1 )
rec_insertion_sort(_lowercase , n - 1 )
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
if index >= len(_lowercase ) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
_A ,_A = (
collection[index],
collection[index - 1],
)
insert_next(_lowercase , index + 1 )
if __name__ == "__main__":
__A = input('Enter integers separated by spaces: ')
__A = [int(num) for num in numbers.split()]
rec_insertion_sort(number_list, len(number_list))
print(number_list)
| 717 |
def __A ( _lowercase ):
'''simple docstring'''
_A = [0] * len(_lowercase )
_A = []
_A = []
_A = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(_lowercase ) ):
if indegree[i] == 0:
queue.append(_lowercase )
while queue:
_A = queue.pop(0 )
cnt += 1
topo.append(_lowercase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(_lowercase )
if cnt != len(_lowercase ):
print('''Cycle exists''' )
else:
print(_lowercase )
# Adjacency List of Graph
__A = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 62 | 0 |
import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path
import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized
from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available
from ..wavaveca.test_feature_extraction_wavaveca import floats_list
if is_pyctcdecode_available():
from huggingface_hub import snapshot_download
from pyctcdecode import BeamSearchDecoderCTC
from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput
if is_torch_available():
from transformers import WavaVecaForCTC
@require_pyctcdecode
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Tuple ) -> Union[str, Any]:
_A = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split()
_A = dict(zip(__A , range(len(__A ) ) ) )
_A = {
'''unk_token''': '''<unk>''',
'''bos_token''': '''<s>''',
'''eos_token''': '''</s>''',
}
_A = {
'''feature_size''': 1,
'''padding_value''': 0.0,
'''sampling_rate''': 1_60_00,
'''return_attention_mask''': False,
'''do_normalize''': True,
}
_A = tempfile.mkdtemp()
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_A = os.path.join(self.tmpdirname , __A )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(__A ) + '''\n''' )
with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(__A ) + '''\n''' )
# load decoder from hub
_A = '''hf-internal-testing/ngram-beam-search-decoder'''
def __A ( self: Any , **__A: str ) -> Union[str, Any]:
_A = self.add_kwargs_tokens_map.copy()
kwargs.update(__A )
return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **__A )
def __A ( self: List[str] , **__A: Optional[Any] ) -> Dict:
return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **__A )
def __A ( self: Optional[Any] , **__A: str ) -> Optional[Any]:
return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **__A )
def __A ( self: Tuple ) -> Dict:
shutil.rmtree(self.tmpdirname )
def __A ( self: Dict ) -> Optional[int]:
_A = self.get_tokenizer()
_A = self.get_feature_extractor()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
processor.save_pretrained(self.tmpdirname )
_A = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname )
# tokenizer
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , __A )
# feature extractor
self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() )
self.assertIsInstance(processor.feature_extractor , __A )
# decoder
self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels )
self.assertEqual(
processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , )
self.assertIsInstance(processor.decoder , __A )
def __A ( self: Any ) -> List[str]:
_A = WavaVecaProcessorWithLM(
tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() )
processor.save_pretrained(self.tmpdirname )
# make sure that error is thrown when decoder alphabet doesn't match
_A = WavaVecaProcessorWithLM.from_pretrained(
self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 )
# decoder
self.assertEqual(processor.language_model.alpha , 5.0 )
self.assertEqual(processor.language_model.beta , 3.0 )
self.assertEqual(processor.language_model.score_boundary , -7.0 )
self.assertEqual(processor.language_model.unk_score_offset , 3 )
def __A ( self: str ) -> int:
_A = self.get_tokenizer()
# add token to trigger raise
tokenizer.add_tokens(['''xx'''] )
with self.assertRaisesRegex(__A , '''include''' ):
WavaVecaProcessorWithLM(
tokenizer=__A , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() )
def __A ( self: int ) -> Dict:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
_A = floats_list((3, 10_00) )
_A = feature_extractor(__A , return_tensors='''np''' )
_A = processor(__A , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def __A ( self: Optional[int] ) -> Optional[int]:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
_A = '''This is a test string'''
_A = processor(text=__A )
_A = tokenizer(__A )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def __A ( self: List[Any] , __A: int=(2, 10, 16) , __A: List[Any]=77 ) -> Dict:
np.random.seed(__A )
return np.random.rand(*__A )
def __A ( self: List[Any] ) -> int:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
_A = self._get_dummy_logits(shape=(10, 16) , seed=13 )
_A = processor.decode(__A )
_A = decoder.decode_beams(__A )[0]
self.assertEqual(decoded_decoder[0] , decoded_processor.text )
self.assertEqual('''</s> <s> </s>''' , decoded_processor.text )
self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score )
self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score )
@parameterized.expand([[None], ['''fork'''], ['''spawn''']] )
def __A ( self: List[Any] , __A: Any ) -> Any:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
_A = self._get_dummy_logits()
# note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
# otherwise, the LM won't be available to the pool's sub-processes.
# manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
if pool_context is None:
_A = processor.batch_decode(__A )
else:
with get_context(__A ).Pool() as pool:
_A = processor.batch_decode(__A , __A )
_A = list(__A )
with get_context('''fork''' ).Pool() as p:
_A = decoder.decode_beams_batch(__A , __A )
_A ,_A ,_A = [], [], []
for beams in decoded_beams:
texts_decoder.append(beams[0][0] )
logit_scores_decoder.append(beams[0][-2] )
lm_scores_decoder.append(beams[0][-1] )
self.assertListEqual(__A , decoded_processor.text )
self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text )
self.assertListEqual(__A , decoded_processor.logit_score )
self.assertListEqual(__A , decoded_processor.lm_score )
def __A ( self: Tuple ) -> Union[str, Any]:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
_A = self._get_dummy_logits()
_A = 15
_A = -20.0
_A = -4.0
_A = processor.batch_decode(
__A , beam_width=__A , beam_prune_logp=__A , token_min_logp=__A , )
_A = decoded_processor_out.text
_A = list(__A )
with get_context('''fork''' ).Pool() as pool:
_A = decoder.decode_beams_batch(
__A , __A , beam_width=__A , beam_prune_logp=__A , token_min_logp=__A , )
_A = [d[0][0] for d in decoded_decoder_out]
_A = [d[0][2] for d in decoded_decoder_out]
_A = [d[0][3] for d in decoded_decoder_out]
self.assertListEqual(__A , __A )
self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , __A )
self.assertTrue(np.array_equal(__A , decoded_processor_out.logit_score ) )
self.assertTrue(np.allclose([-20.054, -18.447] , __A , atol=1e-3 ) )
self.assertTrue(np.array_equal(__A , decoded_processor_out.lm_score ) )
self.assertTrue(np.allclose([-15.554, -13.9_474] , __A , atol=1e-3 ) )
def __A ( self: Dict ) -> Any:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
_A = self._get_dummy_logits()
_A = 2.0
_A = 5.0
_A = -20.0
_A = True
_A = processor.batch_decode(
__A , alpha=__A , beta=__A , unk_score_offset=__A , lm_score_boundary=__A , )
_A = decoded_processor_out.text
_A = list(__A )
decoder.reset_params(
alpha=__A , beta=__A , unk_score_offset=__A , lm_score_boundary=__A , )
with get_context('''fork''' ).Pool() as pool:
_A = decoder.decode_beams_batch(
__A , __A , )
_A = [d[0][0] for d in decoded_decoder_out]
self.assertListEqual(__A , __A )
self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , __A )
_A = processor.decoder.model_container[processor.decoder._model_key]
self.assertEqual(lm_model.alpha , 2.0 )
self.assertEqual(lm_model.beta , 5.0 )
self.assertEqual(lm_model.unk_score_offset , -20.0 )
self.assertEqual(lm_model.score_boundary , __A )
def __A ( self: Union[str, Any] ) -> int:
_A = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_A = processor.decoder.model_container[processor.decoder._model_key]
_A = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute()
_A = os.listdir(__A )
_A = ['''alphabet.json''', '''language_model''']
downloaded_decoder_files.sort()
expected_decoder_files.sort()
# test that only decoder relevant files from
# https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
# are downloaded and none of the rest (e.g. README.md, ...)
self.assertListEqual(__A , __A )
def __A ( self: Optional[int] ) -> Dict:
_A = snapshot_download('''hf-internal-testing/processor_with_lm''' )
_A = WavaVecaProcessorWithLM.from_pretrained(__A )
_A = processor.decoder.model_container[processor.decoder._model_key]
_A = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute()
_A = os.listdir(__A )
_A = os.listdir(__A )
local_decoder_files.sort()
expected_decoder_files.sort()
# test that both decoder form hub and local files in cache are the same
self.assertListEqual(__A , __A )
def __A ( self: Tuple ) -> Optional[Any]:
_A = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_A = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_A = floats_list((3, 10_00) )
_A = processor_wavaveca(__A , return_tensors='''np''' )
_A = processor_auto(__A , return_tensors='''np''' )
for key in input_wavaveca.keys():
self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1e-2 )
_A = self._get_dummy_logits()
_A = processor_wavaveca.batch_decode(__A )
_A = processor_auto.batch_decode(__A )
self.assertListEqual(decoded_wavaveca.text , decoded_auto.text )
def __A ( self: Optional[Any] ) -> int:
_A = self.get_feature_extractor()
_A = self.get_tokenizer()
_A = self.get_decoder()
_A = WavaVecaProcessorWithLM(tokenizer=__A , feature_extractor=__A , decoder=__A )
self.assertListEqual(
processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , )
@staticmethod
def __A ( __A: Any , __A: Tuple ) -> int:
_A = [d[key] for d in offsets]
return retrieved_list
def __A ( self: Dict ) -> List[str]:
_A = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_A = self._get_dummy_logits()[0]
_A = processor.decode(__A , output_word_offsets=__A )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) , 4 )
self.assertTrue('''text''' in outputs )
self.assertTrue('''word_offsets''' in outputs )
self.assertTrue(isinstance(__A , __A ) )
self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) ) , outputs.text )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''start_offset''' ) , [0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''end_offset''' ) , [1, 3, 5] )
def __A ( self: List[str] ) -> List[str]:
_A = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_A = self._get_dummy_logits()
_A = processor.batch_decode(__A , output_word_offsets=__A )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) , 4 )
self.assertTrue('''text''' in outputs )
self.assertTrue('''word_offsets''' in outputs )
self.assertTrue(isinstance(__A , __A ) )
self.assertListEqual(
[''' '''.join(self.get_from_offsets(__A , '''word''' ) ) for o in outputs['''word_offsets''']] , outputs.text )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''start_offset''' ) , [0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''end_offset''' ) , [1, 3, 5] )
@slow
@require_torch
@require_torchaudio
def __A ( self: List[str] ) -> Optional[int]:
import torch
_A = load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=__A )
_A = ds.cast_column('''audio''' , datasets.Audio(sampling_rate=1_60_00 ) )
_A = iter(__A )
_A = next(__A )
_A = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' )
_A = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' )
# compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
_A = processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values
with torch.no_grad():
_A = model(__A ).logits.cpu().numpy()
_A = processor.decode(logits[0] , output_word_offsets=__A )
_A = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
_A = [
{
'''start_time''': d['''start_offset'''] * time_offset,
'''end_time''': d['''end_offset'''] * time_offset,
'''word''': d['''word'''],
}
for d in output['''word_offsets''']
]
_A = '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL'''
# output words
self.assertEqual(''' '''.join(self.get_from_offsets(__A , '''word''' ) ) , __A )
self.assertEqual(''' '''.join(self.get_from_offsets(__A , '''word''' ) ) , output.text )
# output times
_A = torch.tensor(self.get_from_offsets(__A , '''start_time''' ) )
_A = torch.tensor(self.get_from_offsets(__A , '''end_time''' ) )
# fmt: off
_A = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] )
_A = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] )
# fmt: on
self.assertTrue(torch.allclose(__A , __A , atol=0.01 ) )
self.assertTrue(torch.allclose(__A , __A , atol=0.01 ) )
| 718 |
import math
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 SchedulerMixin, SchedulerOutput
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = 1
@register_to_config
def __init__( self: Any , __A: int = 10_00 , __A: Optional[Union[np.ndarray, List[float]]] = None ) -> List[str]:
# set `betas`, `alphas`, `timesteps`
self.set_timesteps(__A )
# standard deviation of the initial noise distribution
_A = 1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
_A = 4
# running values
_A = []
def __A ( self: str , __A: int , __A: Union[str, torch.device] = None ) -> int:
_A = num_inference_steps
_A = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
_A = torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
_A = torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
_A = torch.sin(steps * math.pi / 2 ) ** 2
_A = (1.0 - self.betas**2) ** 0.5
_A = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
_A = timesteps.to(__A )
_A = []
def __A ( self: Tuple , __A: torch.FloatTensor , __A: int , __A: torch.FloatTensor , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
_A = (self.timesteps == timestep).nonzero().item()
_A = timestep_index + 1
_A = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(__A )
if len(self.ets ) == 1:
_A = self.ets[-1]
elif len(self.ets ) == 2:
_A = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
_A = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
_A = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
_A = self._get_prev_sample(__A , __A , __A , __A )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Optional[int] , __A: torch.FloatTensor , *__A: Tuple , **__A: List[Any] ) -> torch.FloatTensor:
return sample
def __A ( self: List[str] , __A: Optional[Any] , __A: Optional[Any] , __A: Any , __A: List[Any] ) -> List[Any]:
_A = self.alphas[timestep_index]
_A = self.betas[timestep_index]
_A = self.alphas[prev_timestep_index]
_A = self.betas[prev_timestep_index]
_A = (sample - sigma * ets) / max(__A , 1e-8 )
_A = next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self: List[str] ) -> Dict:
return self.config.num_train_timesteps
| 62 | 0 |
import os
import tempfile
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from torch import nn
from transformers import (
Adafactor,
AdamW,
get_constant_schedule,
get_constant_schedule_with_warmup,
get_cosine_schedule_with_warmup,
get_cosine_with_hard_restarts_schedule_with_warmup,
get_inverse_sqrt_schedule,
get_linear_schedule_with_warmup,
get_polynomial_decay_schedule_with_warmup,
)
def __A ( _lowercase , _lowercase=10 ):
'''simple docstring'''
_A = []
for _ in range(_lowercase ):
lrs.append(scheduler.get_lr()[0] )
scheduler.step()
return lrs
def __A ( _lowercase , _lowercase=10 ):
'''simple docstring'''
_A = []
for step in range(_lowercase ):
lrs.append(scheduler.get_lr()[0] )
scheduler.step()
if step == num_steps // 2:
with tempfile.TemporaryDirectory() as tmpdirname:
_A = os.path.join(_lowercase , '''schedule.bin''' )
torch.save(scheduler.state_dict() , _lowercase )
_A = torch.load(_lowercase )
scheduler.load_state_dict(_lowercase )
return lrs
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: str , __A: Optional[int] , __A: Optional[int] , __A: Optional[Any] ) -> Optional[int]:
self.assertEqual(len(__A ) , len(__A ) )
for a, b in zip(__A , __A ):
self.assertAlmostEqual(__A , __A , delta=__A )
def __A ( self: Union[str, Any] ) -> Union[str, Any]:
_A = torch.tensor([0.1, -0.2, -0.1] , requires_grad=__A )
_A = torch.tensor([0.4, 0.2, -0.5] )
_A = nn.MSELoss()
# No warmup, constant schedule, no gradient clipping
_A = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 )
for _ in range(1_00 ):
_A = criterion(__A , __A )
loss.backward()
optimizer.step()
w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves.
w.grad.zero_()
self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 )
def __A ( self: Optional[Any] ) -> List[Any]:
_A = torch.tensor([0.1, -0.2, -0.1] , requires_grad=__A )
_A = torch.tensor([0.4, 0.2, -0.5] )
_A = nn.MSELoss()
# No warmup, constant schedule, no gradient clipping
_A = Adafactor(
params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=__A , weight_decay=0.0 , relative_step=__A , scale_parameter=__A , warmup_init=__A , )
for _ in range(10_00 ):
_A = criterion(__A , __A )
loss.backward()
optimizer.step()
w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves.
w.grad.zero_()
self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 )
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
A_ = nn.Linear(50 , 50 ) if is_torch_available() else None
A_ = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None
A_ = 10
def __A ( self: Optional[Any] , __A: List[str] , __A: Optional[Any] , __A: Optional[int] , __A: List[Any]=None ) -> List[Any]:
self.assertEqual(len(__A ) , len(__A ) )
for a, b in zip(__A , __A ):
self.assertAlmostEqual(__A , __A , delta=__A , msg=__A )
def __A ( self: Tuple ) -> List[Any]:
_A = {'''num_warmup_steps''': 2, '''num_training_steps''': 10}
# schedulers doct format
# function: (sched_args_dict, expected_learning_rates)
_A = {
get_constant_schedule: ({}, [10.0] * self.num_steps),
get_constant_schedule_with_warmup: (
{'''num_warmup_steps''': 4},
[0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
),
get_linear_schedule_with_warmup: (
{**common_kwargs},
[0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
),
get_cosine_schedule_with_warmup: (
{**common_kwargs},
[0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
),
get_cosine_with_hard_restarts_schedule_with_warmup: (
{**common_kwargs, '''num_cycles''': 2},
[0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
),
get_polynomial_decay_schedule_with_warmup: (
{**common_kwargs, '''power''': 2.0, '''lr_end''': 1e-7},
[0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156],
),
get_inverse_sqrt_schedule: (
{'''num_warmup_steps''': 2},
[0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714],
),
}
for scheduler_func, data in scheds.items():
_A ,_A = data
_A = scheduler_func(self.optimizer , **__A )
self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 )
_A = unwrap_schedule(__A , self.num_steps )
self.assertListAlmostEqual(
__A , __A , tol=1e-2 , msg=f"""failed for {scheduler_func} in normal scheduler""" , )
_A = scheduler_func(self.optimizer , **__A )
if scheduler_func.__name__ != "get_constant_schedule":
LambdaScheduleWrapper.wrap_scheduler(__A ) # wrap to test picklability of the schedule
_A = unwrap_and_save_reload_schedule(__A , self.num_steps )
self.assertListEqual(__A , __A , msg=f"""failed for {scheduler_func} in save and reload""" )
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: Tuple ) -> Optional[Any]:
_A = fn
def __call__( self: int , *__A: Tuple , **__A: Optional[Any] ) -> Optional[int]:
return self.fn(*__A , **__A )
@classmethod
def __A ( self: Tuple , __A: Dict ) -> List[str]:
_A = list(map(self , scheduler.lr_lambdas ) )
| 719 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A ,_A = len(_lowercase ), len(grid[0] )
if (
min(_lowercase , _lowercase ) < 0
or row == row_length
or col == col_length
or (row, col) in visit
or grid[row][col] == 1
):
return 0
if row == row_length - 1 and col == col_length - 1:
return 1
visit.add((row, col) )
_A = 0
count += depth_first_search(_lowercase , row + 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , row - 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col + 1 , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col - 1 , _lowercase )
visit.remove((row, col) )
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
__A = logging.get_logger(__name__)
__A = {
'''ut/deta''': '''https://huggingface.co/ut/deta/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "deta"
A_ = {
"hidden_size": "d_model",
"num_attention_heads": "encoder_attention_heads",
}
def __init__( self: int , __A: List[str]=None , __A: Optional[int]=9_00 , __A: Dict=20_48 , __A: Union[str, Any]=6 , __A: Union[str, Any]=20_48 , __A: Tuple=8 , __A: Optional[int]=6 , __A: str=10_24 , __A: Optional[Any]=8 , __A: Union[str, Any]=0.0 , __A: Optional[Any]=True , __A: List[Any]="relu" , __A: List[str]=2_56 , __A: Any=0.1 , __A: str=0.0 , __A: List[str]=0.0 , __A: List[Any]=0.02 , __A: List[str]=1.0 , __A: Any=True , __A: Dict=False , __A: List[str]="sine" , __A: Optional[Any]=5 , __A: Union[str, Any]=4 , __A: List[str]=4 , __A: Optional[Any]=True , __A: List[str]=3_00 , __A: List[Any]=True , __A: str=True , __A: Optional[Any]=1 , __A: Dict=5 , __A: int=2 , __A: List[Any]=1 , __A: Any=1 , __A: Tuple=5 , __A: List[Any]=2 , __A: Any=0.1 , __A: Any=0.25 , **__A: int , ) -> Any:
if backbone_config is None:
logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' )
_A = CONFIG_MAPPING['''resnet'''](out_features=['''stage2''', '''stage3''', '''stage4'''] )
else:
if isinstance(__A , __A ):
_A = backbone_config.pop('''model_type''' )
_A = CONFIG_MAPPING[backbone_model_type]
_A = config_class.from_dict(__A )
_A = backbone_config
_A = num_queries
_A = max_position_embeddings
_A = d_model
_A = encoder_ffn_dim
_A = encoder_layers
_A = encoder_attention_heads
_A = decoder_ffn_dim
_A = decoder_layers
_A = decoder_attention_heads
_A = dropout
_A = attention_dropout
_A = activation_dropout
_A = activation_function
_A = init_std
_A = init_xavier_std
_A = encoder_layerdrop
_A = auxiliary_loss
_A = position_embedding_type
# deformable attributes
_A = num_feature_levels
_A = encoder_n_points
_A = decoder_n_points
_A = two_stage
_A = two_stage_num_proposals
_A = with_box_refine
_A = assign_first_stage
if two_stage is True and with_box_refine is False:
raise ValueError('''If two_stage is True, with_box_refine must be True.''' )
# Hungarian matcher
_A = class_cost
_A = bbox_cost
_A = giou_cost
# Loss coefficients
_A = mask_loss_coefficient
_A = dice_loss_coefficient
_A = bbox_loss_coefficient
_A = giou_loss_coefficient
_A = eos_coefficient
_A = focal_alpha
super().__init__(is_encoder_decoder=__A , **__A )
@property
def __A ( self: List[Any] ) -> int:
return self.encoder_attention_heads
@property
def __A ( self: Optional[Any] ) -> int:
return self.d_model
def __A ( self: Union[str, Any] ) -> Optional[int]:
_A = copy.deepcopy(self.__dict__ )
_A = self.backbone_config.to_dict()
_A = self.__class__.model_type
return output
| 720 |
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
__A = NewType('DataClass', Any)
__A = NewType('DataClassType', Any)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , _lowercase ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError(
f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" )
def __A ( _lowercase ):
'''simple docstring'''
_A = {str(_lowercase ): choice for choice in choices}
return lambda _lowercase : str_to_choice.get(_lowercase , _lowercase )
def __A ( *,
_lowercase = None , _lowercase = None , _lowercase = dataclasses.MISSING , _lowercase = dataclasses.MISSING , _lowercase = None , **_lowercase , ):
'''simple docstring'''
if metadata is None:
# Important, don't use as default param in function signature because dict is mutable and shared across function calls
_A = {}
if aliases is not None:
_A = aliases
if help is not None:
_A = help
return dataclasses.field(metadata=_lowercase , default=_lowercase , default_factory=_lowercase , **_lowercase )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = 42
def __init__( self: Optional[Any] , __A: Union[DataClassType, Iterable[DataClassType]] , **__A: List[Any] ) -> str:
# To make the default appear when using --help
if "formatter_class" not in kwargs:
_A = ArgumentDefaultsHelpFormatter
super().__init__(**__A )
if dataclasses.is_dataclass(__A ):
_A = [dataclass_types]
_A = list(__A )
for dtype in self.dataclass_types:
self._add_dataclass_arguments(__A )
@staticmethod
def __A ( __A: ArgumentParser , __A: dataclasses.Field ) -> str:
_A = f"""--{field.name}"""
_A = field.metadata.copy()
# field.metadata is not used at all by Data Classes,
# it is provided as a third-party extension mechanism.
if isinstance(field.type , __A ):
raise RuntimeError(
'''Unresolved type detected, which should have been done with the help of '''
'''`typing.get_type_hints` method by default''' )
_A = kwargs.pop('''aliases''' , [] )
if isinstance(__A , __A ):
_A = [aliases]
_A = getattr(field.type , '''__origin__''' , field.type )
if origin_type is Union or (hasattr(__A , '''UnionType''' ) and isinstance(__A , types.UnionType )):
if str not in field.type.__args__ and (
len(field.type.__args__ ) != 2 or type(__A ) not in field.type.__args__
):
raise ValueError(
'''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
''' the argument parser only supports one type per argument.'''
f""" Problem encountered in field '{field.name}'.""" )
if type(__A ) not in field.type.__args__:
# filter `str` in Union
_A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
_A = getattr(field.type , '''__origin__''' , field.type )
elif bool not in field.type.__args__:
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
_A = (
field.type.__args__[0] if isinstance(__A , field.type.__args__[1] ) else field.type.__args__[1]
)
_A = getattr(field.type , '''__origin__''' , field.type )
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
_A = {}
if origin_type is Literal or (isinstance(field.type , __A ) and issubclass(field.type , __A )):
if origin_type is Literal:
_A = field.type.__args__
else:
_A = [x.value for x in field.type]
_A = make_choice_type_function(kwargs['''choices'''] )
if field.default is not dataclasses.MISSING:
_A = field.default
else:
_A = True
elif field.type is bool or field.type == Optional[bool]:
# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
_A = copy(__A )
# Hack because type=bool in argparse does not behave as we want.
_A = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
_A = False if field.default is dataclasses.MISSING else field.default
# This is the value that will get picked if we don't include --field_name in any way
_A = default
# This tells argparse we accept 0 or 1 value after --field_name
_A = '''?'''
# This is the value that will get picked if we do --field_name (without value)
_A = True
elif isclass(__A ) and issubclass(__A , __A ):
_A = field.type.__args__[0]
_A = '''+'''
if field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
elif field.default is dataclasses.MISSING:
_A = True
else:
_A = field.type
if field.default is not dataclasses.MISSING:
_A = field.default
elif field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
else:
_A = True
parser.add_argument(__A , *__A , **__A )
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need those changes/additional keys.
if field.default is True and (field.type is bool or field.type == Optional[bool]):
_A = False
parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__A )
def __A ( self: Dict , __A: DataClassType ) -> List[Any]:
if hasattr(__A , '''_argument_group_name''' ):
_A = self.add_argument_group(dtype._argument_group_name )
else:
_A = self
try:
_A = get_type_hints(__A )
except NameError:
raise RuntimeError(
f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
'''removing line of `from __future__ import annotations` which opts in Postponed '''
'''Evaluation of Annotations (PEP 563)''' )
except TypeError as ex:
# Remove this block when we drop Python 3.9 support
if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__A ):
_A = '''.'''.join(map(__A , sys.version_info[:3] ) )
raise RuntimeError(
f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
'''line of `from __future__ import annotations` which opts in union types as '''
'''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
'''support Python versions that lower than 3.10, you need to use '''
'''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
'''`X | None`.''' ) from ex
raise
for field in dataclasses.fields(__A ):
if not field.init:
continue
_A = type_hints[field.name]
self._parse_dataclass_field(__A , __A )
def __A ( self: int , __A: Any=None , __A: int=False , __A: Any=True , __A: Optional[Any]=None , __A: Any=None , ) -> Tuple[DataClass, ...]:
if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )):
_A = []
if args_filename:
args_files.append(Path(__A ) )
elif look_for_args_file and len(sys.argv ):
args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) )
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
_A = ArgumentParser()
args_file_parser.add_argument(__A , type=__A , action='''append''' )
# Use only remaining args for further parsing (remove the args_file_flag)
_A ,_A = args_file_parser.parse_known_args(args=__A )
_A = vars(__A ).get(args_file_flag.lstrip('''-''' ) , __A )
if cmd_args_file_paths:
args_files.extend([Path(__A ) for p in cmd_args_file_paths] )
_A = []
for args_file in args_files:
if args_file.exists():
file_args += args_file.read_text().split()
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
_A = file_args + args if args is not None else file_args + sys.argv[1:]
_A ,_A = self.parse_known_args(args=__A )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in vars(__A ).items() if k in keys}
for k in keys:
delattr(__A , __A )
_A = dtype(**__A )
outputs.append(__A )
if len(namespace.__dict__ ) > 0:
# additional namespace.
outputs.append(__A )
if return_remaining_strings:
return (*outputs, remaining_args)
else:
if remaining_args:
raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" )
return (*outputs,)
def __A ( self: Tuple , __A: Dict[str, Any] , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = set(args.keys() )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in args.items() if k in keys}
unused_keys.difference_update(inputs.keys() )
_A = dtype(**__A )
outputs.append(__A )
if not allow_extra_keys and unused_keys:
raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__A )}""" )
return tuple(__A )
def __A ( self: Tuple , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
with open(Path(__A ) , encoding='''utf-8''' ) as open_json_file:
_A = json.loads(open_json_file.read() )
_A = self.parse_dict(__A , allow_extra_keys=__A )
return tuple(__A )
def __A ( self: List[Any] , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = self.parse_dict(yaml.safe_load(Path(__A ).read_text() ) , allow_extra_keys=__A )
return tuple(__A )
| 62 | 0 |
import argparse
import json
import os
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import torch
def __A ( _lowercase ):
_A = os.path.join(args.tf_model_dir , '''parameters.json''' )
_A = json.loads(open(_lowercase ).read() )
if not params:
raise ValueError(
f"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.""" )
if not args.output.endswith('''.pt''' ):
_A = args.output + '''.pt'''
_A = OrderedDict()
with tf.device('''/CPU:0''' ):
_A = tf.train.load_checkpoint(args.tf_model_dir )
_A = reader.get_variable_to_shape_map()
for key_name in shapes.keys():
_A = reader.get_tensor(_lowercase ).astype(np.floataa )
if key_name.endswith('''/adam_m''' ) or key_name.endswith('''/adam_v''' ):
continue
if key_name.startswith('''pasts/''' ):
if key_name.startswith('''pasts/mlp''' ):
_A = int(key_name[9] )
elif key_name.startswith('''pasts/out''' ):
_A = 8
_A = '''model.sqout.%d.weight''' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time
_A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name.startswith('''model/moe''' ):
_A = int(key_name[9:].split('''/''' )[0] )
if key_name.endswith('''/switch_gating/kernel''' ):
_A = '''model.blocks.%d.feed_forward.mlp.router.classifier.weight''' % player
_A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/softmlp/kernel''' ):
_A = '''model.blocks.%d.feed_forward.soft_bypass_mlp.weight''' % player
_A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/wo/kernel''' ) or key_name.endswith('''/wi/kernel''' ):
_A = key_name[-9:-7]
for i in range(16 ):
_A = '''model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight''' % (player, i, nlayer)
_A = (
vnp[i].transpose([1, 0] ).copy()
) # In Mesh-Tensorflow, it is one array, so it is divided
_A = torch.tensor(_lowercase )
elif key_name.startswith('''model/mlp''' ):
_A = int(key_name[9:].split('''/''' )[0] )
if key_name.endswith('''/p1/kernel''' ):
_A = '''model.blocks.%d.feed_forward.mlp.wi.weight''' % player
_A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/p1/bias''' ):
_A = '''model.blocks.%d.feed_forward.mlp.wi.bias''' % player
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/p2/kernel''' ):
_A = '''model.blocks.%d.feed_forward.mlp.wo.weight''' % player
_A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/p2/bias''' ):
_A = '''model.blocks.%d.feed_forward.mlp.wo.bias''' % player
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
elif key_name.startswith('''model/ln''' ):
_A = int(key_name[8:].split('''/''' )[0] )
if key_name.endswith('''/b''' ):
_A = '''model.blocks.%d.feed_forward.norm.bias''' % player
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/g''' ):
_A = '''model.blocks.%d.feed_forward.norm.weight''' % player
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
elif key_name.startswith('''model/att''' ):
_A = int(key_name[9:].split('''/''' )[0] )
if key_name.endswith('''/qkv/kernel''' ):
_A = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum
_A = state[:, 0, :, :]
_A = state[:, 1, :, :]
_A = state[:, 2, :, :]
_A = (
state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
_A = (
state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
_A = (
state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
_A = '''model.blocks.%d.self_attn.self_attn.q_proj.weight''' % player
_A = torch.tensor(_lowercase )
_A = '''model.blocks.%d.self_attn.self_attn.k_proj.weight''' % player
_A = torch.tensor(_lowercase )
_A = '''model.blocks.%d.self_attn.self_attn.v_proj.weight''' % player
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/o/kernel''' ):
_A = '''model.blocks.%d.self_attn.self_attn.out_proj.weight''' % player
_A = (
vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy()
) # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name.startswith('''model/an''' ):
_A = int(key_name[8:].split('''/''' )[0] )
if key_name.endswith('''/b''' ):
_A = '''model.blocks.%d.self_attn.norm.bias''' % player
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
elif key_name.endswith('''/g''' ):
_A = '''model.blocks.%d.self_attn.norm.weight''' % player
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
elif (
key_name.startswith('''model/wte''' )
or key_name.startswith('''model/wpe''' )
or key_name.startswith('''model/ete''' )
):
_A = {'''wte''': '''embed_tokens''', '''wpe''': '''position_embeddings''', '''ete''': '''extra_position_embeddings'''}[
key_name[-3:]
]
_A = '''model.%s.weight''' % nlayer
_A = vnp.copy() # same in embedded
_A = torch.tensor(_lowercase )
if key_name.startswith('''model/wte''' ):
_A = '''lm_head.weight'''
_A = vnp.copy() # same in embedded
_A = torch.tensor(_lowercase )
elif key_name.startswith('''model/wob''' ):
_A = '''final_logits_bias'''
_A = vnp.copy() # same in embedded
_A = state.reshape((1, -1) )
_A = torch.tensor(_lowercase )
elif key_name == "model/dense/kernel":
_A = '''model.last_project.weight'''
_A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
_A = torch.tensor(_lowercase )
elif key_name == "model/dense_1/bias":
_A = '''model.last_project.bias'''
_A = vnp.copy() # same because it is one dimensional
_A = torch.tensor(_lowercase )
torch.save(_lowercase , args.output )
if __name__ == "__main__":
__A = argparse.ArgumentParser(
description='model converter.', formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--tf_model_dir', metavar='PATH', type=str, required=True, help='import model')
parser.add_argument('--output', metavar='PATH', type=str, required=True, help='output model')
__A = parser.parse_args()
convert_tf_gptsan_to_pt(args)
| 721 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: Union[str, Any] , __A: int=2 , __A: List[str]=True , __A: List[Any]=False , __A: Union[str, Any]=10 , __A: Optional[int]=3 , __A: List[Any]=32 * 4 , __A: Dict=32 * 6 , __A: Optional[Any]=4 , __A: Any=32 , ) -> str:
_A = parent
_A = batch_size
_A = is_training
_A = use_auxiliary_loss
_A = num_queries
_A = num_channels
_A = min_size
_A = max_size
_A = num_labels
_A = mask_feature_size
def __A ( self: Dict ) -> Optional[int]:
_A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
__A )
_A = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A )
_A = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5
).float()
_A = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long()
_A = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __A ( self: Optional[Any] ) -> Tuple:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __A ( self: Dict ) -> Tuple:
_A ,_A ,_A ,_A ,_A = self.prepare_config_and_inputs()
_A = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: Dict ) -> int:
_A = output.encoder_hidden_states
_A = output.pixel_decoder_hidden_states
_A = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , config.decoder_config.decoder_layers )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Any , __A: Dict=False ) -> Any:
with torch.no_grad():
_A = MaskFormerModel(config=__A )
model.to(__A )
model.eval()
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A , output_hidden_states=__A )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(__A , __A )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Union[str, Any] , __A: Union[str, Any] , __A: List[Any] ) -> int:
_A = MaskFormerForInstanceSegmentation(config=__A )
model.to(__A )
model.eval()
def comm_check_on_output(__A: int ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A )
comm_check_on_output(__A )
_A = model(
pixel_values=__A , pixel_mask=__A , mask_labels=__A , class_labels=__A )
comm_check_on_output(__A )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
A_ = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
A_ = False
A_ = False
A_ = False
A_ = False
def __A ( self: int ) -> Tuple:
_A = MaskFormerModelTester(self )
_A = ConfigTester(self , config_class=__A , has_text_modality=__A )
def __A ( self: List[Any] ) -> Dict:
self.config_tester.run_common_tests()
def __A ( self: Optional[Any] ) -> int:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Dict ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__A )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def __A ( self: int ) -> Tuple:
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def __A ( self: List[Any] ) -> Any:
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def __A ( self: Union[str, Any] ) -> Optional[int]:
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def __A ( self: int ) -> List[str]:
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def __A ( self: Union[str, Any] ) -> List[Any]:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: List[Any] ) -> Any:
pass
def __A ( self: Dict ) -> Optional[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A )
_A = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_A = [*signature.parameters.keys()]
_A = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __A )
@slow
def __A ( self: int ) -> Optional[Any]:
for model_name in ["facebook/maskformer-swin-small-coco"]:
_A = MaskFormerModel.from_pretrained(__A )
self.assertIsNotNone(__A )
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = (self.model_tester.min_size,) * 2
_A = {
'''pixel_values''': torch.randn((2, 3, *size) , device=__A ),
'''mask_labels''': torch.randn((2, 10, *size) , device=__A ),
'''class_labels''': torch.zeros(2 , 10 , device=__A ).long(),
}
_A = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__A )
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
def __A ( self: Optional[Any] ) -> List[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Any ) -> Tuple:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A ).to(__A )
_A = model(**__A , output_attentions=__A )
self.assertTrue(outputs.attentions is not None )
def __A ( self: Dict ) -> Union[str, Any]:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A ).loss
loss.backward()
def __A ( self: Tuple ) -> Optional[Any]:
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = True
_A = True
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A )
_A = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
_A = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
_A = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
_A = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=__A )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__A = 1e-4
def __A ( ):
'''simple docstring'''
_A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self: Union[str, Any] ) -> Optional[int]:
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def __A ( self: List[Any] ) -> Any:
_A = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(__A )
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
_A = torch.tensor(
[[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Dict ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [
[-1.3_737_124, -1.7_724_937, -1.9_364_233],
[-1.5_977_281, -1.9_867_939, -2.1_523_695],
[-1.5_795_398, -1.9_269_832, -2.093_942],
]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: List[Any] ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Optional[Any] ) -> str:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors='''pt''' , )
_A = inputs['''pixel_values'''].to(__A )
_A = [el.to(__A ) for el in inputs['''mask_labels''']]
_A = [el.to(__A ) for el in inputs['''class_labels''']]
with torch.no_grad():
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
| 62 | 0 |
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 SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = ["image_processor", "tokenizer"]
A_ = "BlipImageProcessor"
A_ = ("BertTokenizer", "BertTokenizerFast")
def __init__( self: str , __A: List[Any] , __A: int ) -> Optional[int]:
_A = False
super().__init__(__A , __A )
_A = self.image_processor
def __call__( self: Any , __A: ImageInput = None , __A: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __A: bool = True , __A: Union[bool, str, PaddingStrategy] = False , __A: Union[bool, str, TruncationStrategy] = None , __A: Optional[int] = None , __A: int = 0 , __A: Optional[int] = None , __A: Optional[bool] = None , __A: bool = False , __A: bool = False , __A: bool = False , __A: bool = False , __A: bool = False , __A: bool = True , __A: Optional[Union[str, TensorType]] = None , **__A: int , ) -> BatchEncoding:
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:
_A = self.tokenizer
_A = self.tokenizer(
text=__A , add_special_tokens=__A , padding=__A , truncation=__A , max_length=__A , stride=__A , pad_to_multiple_of=__A , return_attention_mask=__A , return_overflowing_tokens=__A , return_special_tokens_mask=__A , return_offsets_mapping=__A , return_token_type_ids=__A , return_length=__A , verbose=__A , return_tensors=__A , **__A , )
return text_encoding
# add pixel_values
_A = self.image_processor(__A , return_tensors=__A )
if text is not None:
_A = self.tokenizer(
text=__A , add_special_tokens=__A , padding=__A , truncation=__A , max_length=__A , stride=__A , pad_to_multiple_of=__A , return_attention_mask=__A , return_overflowing_tokens=__A , return_special_tokens_mask=__A , return_offsets_mapping=__A , return_token_type_ids=__A , return_length=__A , verbose=__A , return_tensors=__A , **__A , )
else:
_A = None
if text_encoding is not None:
encoding_image_processor.update(__A )
return encoding_image_processor
def __A ( self: Optional[int] , *__A: Optional[int] , **__A: Optional[Any] ) -> int:
return self.tokenizer.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Any , **__A: List[str] ) -> Union[str, Any]:
return self.tokenizer.decode(*__A , **__A )
@property
def __A ( self: Tuple ) -> Tuple:
_A = self.tokenizer.model_input_names
_A = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 700 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Optional[int] , __A: Optional[Any] ) -> str:
_A = question_encoder
_A = generator
_A = self.question_encoder
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Dict:
if os.path.isfile(__A ):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(__A , exist_ok=__A )
_A = os.path.join(__A , '''question_encoder_tokenizer''' )
_A = os.path.join(__A , '''generator_tokenizer''' )
self.question_encoder.save_pretrained(__A )
self.generator.save_pretrained(__A )
@classmethod
def __A ( cls: Optional[Any] , __A: List[str] , **__A: int ) -> Any:
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
_A = kwargs.pop('''config''' , __A )
if config is None:
_A = RagConfig.from_pretrained(__A )
_A = AutoTokenizer.from_pretrained(
__A , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' )
_A = AutoTokenizer.from_pretrained(
__A , config=config.generator , subfolder='''generator_tokenizer''' )
return cls(question_encoder=__A , generator=__A )
def __call__( self: int , *__A: Optional[int] , **__A: List[str] ) -> int:
return self.current_tokenizer(*__A , **__A )
def __A ( self: Dict , *__A: List[str] , **__A: List[str] ) -> Dict:
return self.generator.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Tuple , **__A: List[str] ) -> Tuple:
return self.generator.decode(*__A , **__A )
def __A ( self: Dict ) -> List[str]:
_A = self.question_encoder
def __A ( self: Union[str, Any] ) -> int:
_A = self.generator
def __A ( self: Dict , __A: List[str] , __A: Optional[List[str]] = None , __A: Optional[int] = None , __A: Optional[int] = None , __A: str = "longest" , __A: str = None , __A: bool = True , **__A: Tuple , ) -> BatchEncoding:
warnings.warn(
'''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
'''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
'''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
'''details''' , __A , )
if max_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
__A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , )
_A = labels['''input_ids''']
return model_inputs
| 62 | 0 |
import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional
import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset
import transformers
from transformers import (
AutoConfig,
AutoFeatureExtractor,
AutoModelForAudioClassification,
HfArgumentParser,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__A = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')
require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt')
def __A ( _lowercase , _lowercase , _lowercase = 1_60_00 ):
'''simple docstring'''
_A = int(round(sample_rate * max_length ) )
if len(_lowercase ) <= sample_length:
return wav
_A = randint(0 , len(_lowercase ) - sample_length - 1 )
return wav[random_offset : random_offset + sample_length]
@dataclass
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
A_ = field(default=snake_case , metadata={"help": "Name of a dataset from the datasets package"} )
A_ = field(
default=snake_case , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} )
A_ = field(
default=snake_case , metadata={"help": "A file containing the training audio paths and labels."} )
A_ = field(
default=snake_case , metadata={"help": "A file containing the validation audio paths and labels."} )
A_ = field(
default="train" , metadata={
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
} , )
A_ = field(
default="validation" , metadata={
"help": (
"The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
)
} , )
A_ = field(
default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , )
A_ = field(
default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} )
A_ = field(
default=snake_case , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
} , )
A_ = field(
default=snake_case , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
} , )
A_ = field(
default=20 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , )
@dataclass
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
A_ = field(
default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , )
A_ = field(
default=snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} )
A_ = field(
default=snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} )
A_ = field(
default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , )
A_ = field(
default=snake_case , metadata={"help": "Name or path of preprocessor config."} )
A_ = field(
default=snake_case , metadata={"help": "Whether to freeze the feature encoder layers of the model."} )
A_ = field(
default=snake_case , metadata={"help": "Whether to generate an attention mask in the feature extractor."} )
A_ = field(
default=snake_case , metadata={
"help": (
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
"with private models)."
)
} , )
A_ = field(
default=snake_case , metadata={"help": "Whether to freeze the feature extractor layers of the model."} )
A_ = field(
default=snake_case , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , )
def __A ( self: Optional[Any] ) -> List[Any]:
if not self.freeze_feature_extractor and self.freeze_feature_encoder:
warnings.warn(
'''The argument `--freeze_feature_extractor` is deprecated and '''
'''will be removed in a future version. Use `--freeze_feature_encoder`'''
'''instead. Setting `freeze_feature_encoder==True`.''' , __A , )
if self.freeze_feature_extractor and not self.freeze_feature_encoder:
raise ValueError(
'''The argument `--freeze_feature_extractor` is deprecated and '''
'''should not be used in combination with `--freeze_feature_encoder`.'''
'''Only make use of `--freeze_feature_encoder`.''' )
def __A ( ):
'''simple docstring'''
_A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
_A ,_A ,_A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
_A ,_A ,_A = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry('''run_audio_classification''' , _lowercase , _lowercase )
# Setup logging
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , )
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
_A = training_args.get_process_log_level()
logger.setLevel(_lowercase )
transformers.utils.logging.set_verbosity(_lowercase )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """
+ f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" )
logger.info(f"""Training/evaluation parameters {training_args}""" )
# Set seed before initializing model.
set_seed(training_args.seed )
# Detecting last checkpoint.
_A = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
_A = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
'''Use --overwrite_output_dir to train from scratch.''' )
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
'''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' )
# Initialize our dataset and prepare it for the audio classification task.
_A = DatasetDict()
_A = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , )
_A = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , )
if data_args.audio_column_name not in raw_datasets["train"].column_names:
raise ValueError(
f"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """
'''Make sure to set `--audio_column_name` to the correct audio column - one of '''
f"""{", ".join(raw_datasets["train"].column_names )}.""" )
if data_args.label_column_name not in raw_datasets["train"].column_names:
raise ValueError(
f"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """
'''Make sure to set `--label_column_name` to the correct text column - one of '''
f"""{", ".join(raw_datasets["train"].column_names )}.""" )
# Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
# transformer outputs in the classifier, but it doesn't always lead to better accuracy
_A = AutoFeatureExtractor.from_pretrained(
model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
# `datasets` takes care of automatically loading and resampling the audio,
# so we just need to set the correct target sampling rate.
_A = raw_datasets.cast_column(
data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) )
_A = feature_extractor.model_input_names[0]
def train_transforms(_lowercase ):
_A = []
for audio in batch[data_args.audio_column_name]:
_A = random_subsample(
audio['''array'''] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate )
subsampled_wavs.append(_lowercase )
_A = feature_extractor(_lowercase , sampling_rate=feature_extractor.sampling_rate )
_A = {model_input_name: inputs.get(_lowercase )}
_A = list(batch[data_args.label_column_name] )
return output_batch
def val_transforms(_lowercase ):
_A = [audio['''array'''] for audio in batch[data_args.audio_column_name]]
_A = feature_extractor(_lowercase , sampling_rate=feature_extractor.sampling_rate )
_A = {model_input_name: inputs.get(_lowercase )}
_A = list(batch[data_args.label_column_name] )
return output_batch
# Prepare label mappings.
# We'll include these in the model's config to get human readable labels in the Inference API.
_A = raw_datasets['''train'''].features[data_args.label_column_name].names
_A ,_A = {}, {}
for i, label in enumerate(_lowercase ):
_A = str(_lowercase )
_A = label
# Load the accuracy metric from the datasets package
_A = evaluate.load('''accuracy''' )
# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
# `predictions` and `label_ids` fields) and has to return a dictionary string to float.
def compute_metrics(_lowercase ):
_A = np.argmax(eval_pred.predictions , axis=1 )
return metric.compute(predictions=_lowercase , references=eval_pred.label_ids )
_A = AutoConfig.from_pretrained(
model_args.config_name or model_args.model_name_or_path , num_labels=len(_lowercase ) , labelaid=_lowercase , idalabel=_lowercase , finetuning_task='''audio-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
_A = AutoModelForAudioClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , )
# freeze the convolutional waveform encoder
if model_args.freeze_feature_encoder:
model.freeze_feature_encoder()
if training_args.do_train:
if data_args.max_train_samples is not None:
_A = (
raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) )
)
# Set the training transforms
raw_datasets["train"].set_transform(_lowercase , output_all_columns=_lowercase )
if training_args.do_eval:
if data_args.max_eval_samples is not None:
_A = (
raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) )
)
# Set the validation transforms
raw_datasets["eval"].set_transform(_lowercase , output_all_columns=_lowercase )
# Initialize our trainer
_A = Trainer(
model=_lowercase , args=_lowercase , train_dataset=raw_datasets['''train'''] if training_args.do_train else None , eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None , compute_metrics=_lowercase , tokenizer=_lowercase , )
# Training
if training_args.do_train:
_A = None
if training_args.resume_from_checkpoint is not None:
_A = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
_A = last_checkpoint
_A = trainer.train(resume_from_checkpoint=_lowercase )
trainer.save_model()
trainer.log_metrics('''train''' , train_result.metrics )
trainer.save_metrics('''train''' , train_result.metrics )
trainer.save_state()
# Evaluation
if training_args.do_eval:
_A = trainer.evaluate()
trainer.log_metrics('''eval''' , _lowercase )
trainer.save_metrics('''eval''' , _lowercase )
# Write model card and (optionally) push to hub
_A = {
'''finetuned_from''': model_args.model_name_or_path,
'''tasks''': '''audio-classification''',
'''dataset''': data_args.dataset_name,
'''tags''': ['''audio-classification'''],
}
if training_args.push_to_hub:
trainer.push_to_hub(**_lowercase )
else:
trainer.create_model_card(**_lowercase )
if __name__ == "__main__":
main()
| 701 |
from __future__ import annotations
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ): # noqa: E741
'''simple docstring'''
while r - l > 1:
_A = (l + r) // 2
if v[m] >= key:
_A = m
else:
_A = m # noqa: E741
return r
def __A ( _lowercase ):
'''simple docstring'''
if len(_lowercase ) == 0:
return 0
_A = [0] * len(_lowercase )
_A = 1
_A = v[0]
for i in range(1 , len(_lowercase ) ):
if v[i] < tail[0]:
_A = v[i]
elif v[i] > tail[length - 1]:
_A = v[i]
length += 1
else:
_A = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
from __future__ import annotations
__A = [
[-1, 0], # left
[0, -1], # down
[1, 0], # right
[0, 1], # up
]
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ):
'''simple docstring'''
_A = [
[0 for col in range(len(grid[0] ) )] for row in range(len(_lowercase ) )
] # the reference grid
_A = 1
_A = [
[0 for col in range(len(grid[0] ) )] for row in range(len(_lowercase ) )
] # the action grid
_A = init[0]
_A = init[1]
_A = 0
_A = g + heuristic[x][y] # cost from starting cell to destination cell
_A = [[f, g, x, y]]
_A = False # flag that is set when search is complete
_A = False # flag set if we can't find expand
while not found and not resign:
if len(_lowercase ) == 0:
raise ValueError('''Algorithm is unable to find solution''' )
else: # to choose the least costliest action so as to move closer to the goal
cell.sort()
cell.reverse()
_A = cell.pop()
_A = next_cell[2]
_A = next_cell[3]
_A = next_cell[1]
if x == goal[0] and y == goal[1]:
_A = True
else:
for i in range(len(_lowercase ) ): # to try out different valid actions
_A = x + DIRECTIONS[i][0]
_A = y + DIRECTIONS[i][1]
if xa >= 0 and xa < len(_lowercase ) and ya >= 0 and ya < len(grid[0] ):
if closed[xa][ya] == 0 and grid[xa][ya] == 0:
_A = g + cost
_A = ga + heuristic[xa][ya]
cell.append([fa, ga, xa, ya] )
_A = 1
_A = i
_A = []
_A = goal[0]
_A = goal[1]
invpath.append([x, y] ) # we get the reverse path from here
while x != init[0] or y != init[1]:
_A = x - DIRECTIONS[action[x][y]][0]
_A = y - DIRECTIONS[action[x][y]][1]
_A = xa
_A = ya
invpath.append([x, y] )
_A = []
for i in range(len(_lowercase ) ):
path.append(invpath[len(_lowercase ) - 1 - i] )
return path, action
if __name__ == "__main__":
__A = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
]
__A = [0, 0]
# all coordinates are given in format [y,x]
__A = [len(grid) - 1, len(grid[0]) - 1]
__A = 1
# the cost map which pushes the path closer to the goal
__A = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
__A = abs(i - goal[0]) + abs(j - goal[1])
if grid[i][j] == 1:
# added extra penalty in the heuristic map
__A = 99
__A , __A = search(grid, init, goal, cost, heuristic)
print('ACTION MAP')
for i in range(len(action)):
print(action[i])
for i in range(len(path)):
print(path[i])
| 702 |
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
__A = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "sequence-classification"
def __init__( self: str , __A: Union[str, Any] ) -> List[str]:
if type(__A ) == dict:
_A = Namespace(**__A )
_A = glue_output_modes[hparams.task]
_A = glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def __A ( self: Optional[Any] , **__A: Union[str, Any] ) -> Optional[int]:
return self.model(**__A )
def __A ( self: Any , __A: Union[str, Any] , __A: int ) -> Optional[Any]:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A = outputs[0]
_A = self.trainer.lr_schedulers[0]['''scheduler''']
_A = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def __A ( self: List[str] ) -> Dict:
_A = self.hparams
_A = processors[args.task]()
_A = processor.get_labels()
for mode in ["train", "dev"]:
_A = self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('''Loading features from cached file %s''' , __A )
else:
logger.info('''Creating features from dataset file at %s''' , args.data_dir )
_A = (
processor.get_dev_examples(args.data_dir )
if mode == '''dev'''
else processor.get_train_examples(args.data_dir )
)
_A = convert_examples_to_features(
__A , 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''' , __A )
torch.save(__A , __A )
def __A ( self: List[str] , __A: str , __A: int , __A: bool = False ) -> DataLoader:
_A = '''dev''' if mode == '''test''' else mode
_A = self._feature_file(__A )
logger.info('''Loading features from cached file %s''' , __A )
_A = torch.load(__A )
_A = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_A = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_A = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_A = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_A = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def __A ( self: List[str] , __A: str , __A: Tuple ) -> str:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A ,_A = outputs[:2]
_A = logits.detach().cpu().numpy()
_A = inputs['''labels'''].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __A ( self: str , __A: Dict ) -> tuple:
_A = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item()
_A = np.concatenate([x['''pred'''] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_A = np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_A = np.squeeze(__A )
_A = np.concatenate([x['''target'''] for x in outputs] , axis=0 )
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_A = dict(results.items() )
_A = results
return ret, preds_list, out_label_list
def __A ( self: Any , __A: list ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = ret['''log''']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __A ( self: int , __A: Union[str, Any] ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = 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 ( __A: Optional[Any] , __A: Optional[Any] ) -> Optional[Any]:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'''--max_seq_length''' , default=1_28 , type=__A , 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=__A , required=__A , help='''The GLUE task to run''' , )
parser.add_argument(
'''--gpus''' , default=0 , type=__A , 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 __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser()
add_generic_args(_lowercase , os.getcwd() )
_A = GLUETransformer.add_model_specific_args(_lowercase , os.getcwd() )
_A = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_A = os.path.join(
'''./results''' , f"""{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}""" , )
os.makedirs(args.output_dir )
_A = GLUETransformer(_lowercase )
_A = generic_train(_lowercase , _lowercase )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_A = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=_lowercase ) )
_A = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(_lowercase )
if __name__ == "__main__":
main()
| 62 | 0 |
import os
def __A ( _lowercase = "input.txt" ):
'''simple docstring'''
with open(os.path.join(os.path.dirname(_lowercase ) , _lowercase ) ) as input_file:
_A = [
[int(_lowercase ) for element in line.split(''',''' )]
for line in input_file.readlines()
]
_A = len(_lowercase )
_A = len(matrix[0] )
_A = [[-1 for _ in range(_lowercase )] for _ in range(_lowercase )]
for i in range(_lowercase ):
_A = matrix[i][0]
for j in range(1 , _lowercase ):
for i in range(_lowercase ):
_A = minimal_path_sums[i][j - 1] + matrix[i][j]
for i in range(1 , _lowercase ):
_A = min(
minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] )
for i in range(rows - 2 , -1 , -1 ):
_A = min(
minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] )
return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums )
if __name__ == "__main__":
print(f'{solution() = }')
| 703 |
from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def __A ( _lowercase = "" ):
'''simple docstring'''
_A = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250'''
_A = BeautifulSoup(requests.get(_lowercase ).text , '''html.parser''' )
_A = soup.find_all('''td''' , attrs='''titleColumn''' )
_A = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' )
return {
title.a.text: float(rating.strong.text )
for title, rating in zip(_lowercase , _lowercase )
}
def __A ( _lowercase = "IMDb_Top_250_Movies.csv" ):
'''simple docstring'''
_A = get_imdb_top_aaa_movies()
with open(_lowercase , '''w''' , newline='''''' ) as out_file:
_A = csv.writer(_lowercase )
writer.writerow(['''Movie title''', '''IMDb rating'''] )
for title, rating in movies.items():
writer.writerow([title, rating] )
if __name__ == "__main__":
write_movies()
| 62 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'transfo-xl-wt103': 'https://huggingface.co/transfo-xl-wt103/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "transfo-xl"
A_ = ["mems"]
A_ = {
"n_token": "vocab_size",
"hidden_size": "d_model",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__( self: int , __A: str=26_77_35 , __A: Tuple=[2_00_00, 4_00_00, 20_00_00] , __A: Any=10_24 , __A: int=10_24 , __A: Optional[int]=16 , __A: List[str]=64 , __A: List[Any]=40_96 , __A: Optional[int]=4 , __A: Optional[int]=False , __A: str=18 , __A: str=16_00 , __A: str=10_00 , __A: Optional[Any]=True , __A: Optional[int]=True , __A: Optional[Any]=0 , __A: Optional[int]=-1 , __A: int=True , __A: Optional[int]=0.1 , __A: Dict=0.0 , __A: Optional[Any]=True , __A: int="normal" , __A: Any=0.01 , __A: Optional[Any]=0.01 , __A: Optional[int]=0.02 , __A: Dict=1e-5 , __A: List[Any]=0 , **__A: Tuple , ) -> Dict:
_A = vocab_size
_A = []
self.cutoffs.extend(__A )
if proj_share_all_but_first:
_A = [False] + [True] * len(self.cutoffs )
else:
_A = [False] + [False] * len(self.cutoffs )
_A = d_model
_A = d_embed
_A = d_head
_A = d_inner
_A = div_val
_A = pre_lnorm
_A = n_layer
_A = n_head
_A = mem_len
_A = same_length
_A = attn_type
_A = clamp_len
_A = sample_softmax
_A = adaptive
_A = dropout
_A = dropatt
_A = untie_r
_A = init
_A = init_range
_A = proj_init_std
_A = init_std
_A = layer_norm_epsilon
super().__init__(eos_token_id=__A , **__A )
@property
def __A ( self: Any ) -> Optional[int]:
# Message copied from Transformer-XL documentation
logger.info(f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
return -1
@max_position_embeddings.setter
def __A ( self: Union[str, Any] , __A: Tuple ) -> Optional[Any]:
# Message copied from Transformer-XL documentation
raise NotImplementedError(
f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
| 704 |
import json
import os
import unittest
from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
VOCAB_FILES_NAMES,
BlenderbotSmallTokenizer,
)
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = BlenderbotSmallTokenizer
A_ = False
def __A ( self: List[str] ) -> int:
super().setUp()
_A = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__''']
_A = dict(zip(__A , range(len(__A ) ) ) )
_A = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', '''''']
_A = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''}
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_A = 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 __A ( self: str , **__A: Optional[Any] ) -> Dict:
kwargs.update(self.special_tokens_map )
return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__A )
def __A ( self: str , __A: List[str] ) -> int:
_A = '''adapt act apte'''
_A = '''adapt act apte'''
return input_text, output_text
def __A ( self: Union[str, Any] ) -> Any:
_A = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_A = '''adapt act apte'''
_A = ['''adapt''', '''act''', '''ap@@''', '''te''']
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , __A )
_A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
_A = [0, 1, 2, 3, 4, 5]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
def __A ( self: Any ) -> List[str]:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
assert tok('''sam''' ).input_ids == [13_84]
_A = '''I am a small frog.'''
_A = tok([src_text] , padding=__A , truncation=__A )['''input_ids''']
_A = tok.batch_decode(__A , skip_special_tokens=__A , clean_up_tokenization_spaces=__A )[0]
assert src_text != decoded # I wish it did!
assert decoded == "i am a small frog ."
def __A ( self: Any ) -> int:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
_A = '''I am a small frog .'''
_A = '''.'''
_A = tok(__A )['''input_ids''']
_A = tok(__A )['''input_ids''']
assert encoded[-1] == encoded_dot[0]
| 62 | 0 |
import warnings
from .generation import TFGenerationMixin
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
warnings.warn(
"Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will "
"be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead." , snake_case , )
| 705 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json',
'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "roberta"
def __init__( self: Dict , __A: int=5_02_65 , __A: Union[str, Any]=7_68 , __A: Union[str, Any]=12 , __A: str=12 , __A: int=30_72 , __A: str="gelu" , __A: Union[str, Any]=0.1 , __A: int=0.1 , __A: Optional[int]=5_12 , __A: Union[str, Any]=2 , __A: str=0.02 , __A: str=1e-12 , __A: Any=1 , __A: str=0 , __A: Any=2 , __A: Optional[int]="absolute" , __A: Optional[Any]=True , __A: Union[str, Any]=None , **__A: List[str] , ) -> Dict:
super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
_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 SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
def __A ( self: Dict ) -> Mapping[str, Mapping[int, str]]:
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),
] )
| 62 | 0 |
from __future__ import annotations
import time
from math import sqrt
# 1 for manhattan, 0 for euclidean
__A = 0
__A = [
[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 = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
__A = tuple[int, int]
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Union[str, Any] , __A: int , __A: int , __A: int , __A: int , __A: int , __A: Node | None , ) -> None:
_A = pos_x
_A = pos_y
_A = (pos_y, pos_x)
_A = goal_x
_A = goal_y
_A = g_cost
_A = parent
_A = self.calculate_heuristic()
_A = self.g_cost + self.h_cost
def __A ( self: int ) -> float:
_A = self.pos_x - self.goal_x
_A = self.pos_y - self.goal_y
if HEURISTIC == 1:
return abs(__A ) + abs(__A )
else:
return sqrt(dy**2 + dx**2 )
def __lt__( self: List[str] , __A: Node ) -> bool:
return self.f_cost < other.f_cost
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: TPosition , __A: TPosition ) -> str:
_A = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __A )
_A = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , __A )
_A = [self.start]
_A = []
_A = False
def __A ( self: Optional[Any] ) -> list[TPosition]:
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
_A = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
return self.retrace_path(__A )
self.closed_nodes.append(__A )
_A = self.get_successors(__A )
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(__A )
else:
# retrieve the best current path
_A = self.open_nodes.pop(self.open_nodes.index(__A ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(__A )
else:
self.open_nodes.append(__A )
return [self.start.pos]
def __A ( self: str , __A: Node ) -> list[Node]:
_A = []
for action in delta:
_A = parent.pos_x + action[1]
_A = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__A ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
__A , __A , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __A , ) )
return successors
def __A ( self: str , __A: Node | None ) -> list[TPosition]:
_A = node
_A = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
_A = current_node.parent
path.reverse()
return path
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Union[str, Any] , __A: TPosition , __A: TPosition ) -> None:
_A = AStar(__A , __A )
_A = AStar(__A , __A )
_A = False
def __A ( self: Tuple ) -> 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()
_A = self.fwd_astar.open_nodes.pop(0 )
_A = self.bwd_astar.open_nodes.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
return self.retrace_bidirectional_path(
__A , __A )
self.fwd_astar.closed_nodes.append(__A )
self.bwd_astar.closed_nodes.append(__A )
_A = current_bwd_node
_A = current_fwd_node
_A = {
self.fwd_astar: self.fwd_astar.get_successors(__A ),
self.bwd_astar: self.bwd_astar.get_successors(__A ),
}
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(__A )
else:
# retrieve the best current path
_A = astar.open_nodes.pop(
astar.open_nodes.index(__A ) )
if child_node.g_cost < better_node.g_cost:
astar.open_nodes.append(__A )
else:
astar.open_nodes.append(__A )
return [self.fwd_astar.start.pos]
def __A ( self: List[str] , __A: Node , __A: Node ) -> list[TPosition]:
_A = self.fwd_astar.retrace_path(__A )
_A = self.bwd_astar.retrace_path(__A )
bwd_path.pop()
bwd_path.reverse()
_A = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
__A = (0, 0)
__A = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
__A = time.time()
__A = AStar(init, goal)
__A = a_star.search()
__A = time.time() - start_time
print(f'AStar execution time = {end_time:f} seconds')
__A = time.time()
__A = BidirectionalAStar(init, goal)
__A = time.time() - bd_start_time
print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
| 706 |
import logging
import os
import quant_trainer
import torch
from torch.utils.data import DataLoader
from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput
__A = logging.getLogger(__name__)
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: int , *__A: str , __A: List[Any]=None , __A: Union[str, Any]=None , __A: List[Any]=None , **__A: int ) -> List[Any]:
super().__init__(*__A , **__A )
_A = eval_examples
_A = post_process_function
_A = quant_trainer_args
_A = 1_28 # default number of calibration samples
def __A ( self: Union[str, Any] , __A: List[Any]=None ) -> Optional[Any]:
if calib_dataset is None and self.calib_dataset is None:
raise ValueError('''Trainer: calibration requires an calib_dataset.''' )
_A = calib_dataset if calib_dataset is not None else self.calib_dataset
_A = self._remove_unused_columns(__A , description='''Calibration''' )
return DataLoader(
__A , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__A , )
def __A ( self: List[Any] , __A: Any=None ) -> Optional[int]:
_A = self.train_dataset if calib_dataset is None else calib_dataset
_A = self.get_calib_dataloader(__A )
_A = self.model
quant_trainer.configure_model(__A , self.quant_trainer_args , calib=__A )
model.eval()
quant_trainer.enable_calibration(__A )
logger.info('''***** Running calibration *****''' )
logger.info(f""" Num examples = {self.calib_num}""" )
logger.info(f""" Batch size = {calib_dataloader.batch_size}""" )
for step, inputs in enumerate(__A ):
# Prediction step
_A ,_A ,_A = self.prediction_step(__A , __A , prediction_loss_only=__A )
if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
break
quant_trainer.finish_calibration(__A , self.quant_trainer_args )
_A = model
def __A ( self: Any , __A: Dict=None , __A: Tuple=None , __A: List[Any]=None , __A: str = "eval" ) -> int:
_A = self.eval_dataset if eval_dataset is None else eval_dataset
_A = self.get_eval_dataloader(__A )
_A = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is not None and self.compute_metrics is not None:
_A = self.post_process_function(__A , __A , output.predictions )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
self.log(__A )
else:
_A = {}
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
_A = self.callback_handler.on_evaluate(self.args , self.state , self.control , __A )
return metrics
def __A ( self: Union[str, Any] , __A: Optional[int] , __A: int , __A: List[Any]=None , __A: str = "test" ) -> Union[str, Any]:
_A = self.get_test_dataloader(__A )
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is None or self.compute_metrics is None:
return output
_A = self.post_process_function(__A , __A , output.predictions , '''predict''' )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__A )
def __A ( self: Tuple , __A: Optional[Any]="./" ) -> List[str]:
_A = self.eval_dataset
_A = self.get_eval_dataloader(__A )
_A = next(iter(__A ) )
# saving device - to make it consistent
_A = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' )
# convert to tuple
_A = tuple(v.to(__A ) for k, v in batch.items() )
logger.info('''Converting model to be onnx compatible''' )
from pytorch_quantization.nn import TensorQuantizer
_A = True
_A = self.model.to(__A )
model.eval()
model.float()
_A = model.module if hasattr(__A , '''module''' ) else model
quant_trainer.configure_model(__A , self.quant_trainer_args )
_A = os.path.join(__A , '''model.onnx''' )
logger.info(f"""exporting model to {output_model_file}""" )
_A = {0: '''batch_size''', 1: '''seq_len'''}
torch.onnx.export(
__A , __A , __A , export_params=__A , opset_version=13 , do_constant_folding=__A , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={
'''input_ids''': axes,
'''attention_mask''': axes,
'''token_type_ids''': axes,
'''output_start_logits''': axes,
'''output_end_logits''': axes,
} , verbose=__A , )
logger.info('''onnx export finished''' )
| 62 | 0 |
from __future__ import annotations
__A = 1.6021e-19 # units = C
def __A ( _lowercase , _lowercase , _lowercase , ):
'''simple docstring'''
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()
| 707 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__A = {
'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MegaForCausalLM',
'MegaForMaskedLM',
'MegaForMultipleChoice',
'MegaForQuestionAnswering',
'MegaForSequenceClassification',
'MegaForTokenClassification',
'MegaModel',
'MegaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 62 | 0 |
import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch
import datasets
import datasets.config
from .utils import require_beam
class SCREAMING_SNAKE_CASE ( datasets.BeamBasedBuilder ):
"""simple docstring"""
def __A ( self: Dict ) -> int:
return datasets.DatasetInfo(
features=datasets.Features({'''content''': datasets.Value('''string''' )} ) , supervised_keys=__A , )
def __A ( self: Optional[int] , __A: Any , __A: List[str] ) -> str:
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_dummy_examples()} )]
def __A ( self: List[str] , __A: str , __A: List[str] ) -> Dict:
import apache_beam as beam
return pipeline | "Load Examples" >> beam.Create(__A )
class SCREAMING_SNAKE_CASE ( datasets.BeamBasedBuilder ):
"""simple docstring"""
def __A ( self: Optional[Any] ) -> Optional[int]:
return datasets.DatasetInfo(
features=datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) , supervised_keys=__A , )
def __A ( self: int , __A: str , __A: str ) -> Tuple:
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''examples''': get_test_nested_examples()} )
]
def __A ( self: Optional[Any] , __A: Dict , __A: int ) -> Tuple:
import apache_beam as beam
return pipeline | "Load Examples" >> beam.Create(__A )
def __A ( ):
'''simple docstring'''
return [(i, {"content": content}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )]
def __A ( ):
'''simple docstring'''
return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['''foo''', '''bar''', '''foobar'''] )]
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@require_beam
def __A ( self: Union[str, Any] ) -> str:
_A = len(get_test_dummy_examples() )
with tempfile.TemporaryDirectory() as tmp_cache_dir:
_A = DummyBeamDataset(cache_dir=__A , beam_runner='''DirectRunner''' )
builder.download_and_prepare()
self.assertTrue(
os.path.exists(
os.path.join(__A , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train.arrow""" ) ) )
self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) )
_A = builder.as_dataset()
self.assertEqual(dset['''train'''].num_rows , __A )
self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , __A )
self.assertDictEqual(dset['''train'''][0] , get_test_dummy_examples()[0][1] )
self.assertDictEqual(
dset['''train'''][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] )
self.assertTrue(
os.path.exists(os.path.join(__A , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) )
del dset
@require_beam
def __A ( self: Tuple ) -> Dict:
import apache_beam as beam
_A = beam.io.parquetio.WriteToParquet
_A = len(get_test_dummy_examples() )
with tempfile.TemporaryDirectory() as tmp_cache_dir:
_A = DummyBeamDataset(cache_dir=__A , beam_runner='''DirectRunner''' )
with patch('''apache_beam.io.parquetio.WriteToParquet''' ) as write_parquet_mock:
_A = partial(__A , num_shards=2 )
builder.download_and_prepare()
self.assertTrue(
os.path.exists(
os.path.join(
__A , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train-00000-of-00002.arrow""" ) ) )
self.assertTrue(
os.path.exists(
os.path.join(
__A , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train-00000-of-00002.arrow""" ) ) )
self.assertDictEqual(builder.info.features , datasets.Features({'''content''': datasets.Value('''string''' )} ) )
_A = builder.as_dataset()
self.assertEqual(dset['''train'''].num_rows , __A )
self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , __A )
# Order is not preserved when sharding, so we just check that all the elements are there
self.assertListEqual(sorted(dset['''train''']['''content'''] ) , sorted(['''foo''', '''bar''', '''foobar'''] ) )
self.assertTrue(
os.path.exists(os.path.join(__A , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) )
del dset
@require_beam
def __A ( self: List[str] ) -> int:
with tempfile.TemporaryDirectory() as tmp_cache_dir:
_A = DummyBeamDataset(cache_dir=__A )
self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare )
@require_beam
def __A ( self: List[str] ) -> List[Any]:
_A = len(get_test_nested_examples() )
with tempfile.TemporaryDirectory() as tmp_cache_dir:
_A = NestedBeamDataset(cache_dir=__A , beam_runner='''DirectRunner''' )
builder.download_and_prepare()
self.assertTrue(
os.path.exists(
os.path.join(__A , builder.name , '''default''' , '''0.0.0''' , f"""{builder.name}-train.arrow""" ) ) )
self.assertDictEqual(
builder.info.features , datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string''' )} )} ) )
_A = builder.as_dataset()
self.assertEqual(dset['''train'''].num_rows , __A )
self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples , __A )
self.assertDictEqual(dset['''train'''][0] , get_test_nested_examples()[0][1] )
self.assertDictEqual(
dset['''train'''][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] )
self.assertTrue(
os.path.exists(os.path.join(__A , builder.name , '''default''' , '''0.0.0''' , '''dataset_info.json''' ) ) )
del dset
| 708 |
import itertools
import string
from collections.abc import Generator, Iterable
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = iter(_lowercase )
while True:
_A = tuple(itertools.islice(_lowercase , _lowercase ) )
if not chunk:
return
yield chunk
def __A ( _lowercase ):
'''simple docstring'''
_A = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] )
_A = ''''''
if len(_lowercase ) < 2:
return dirty
for i in range(len(_lowercase ) - 1 ):
clean += dirty[i]
if dirty[i] == dirty[i + 1]:
clean += "X"
clean += dirty[-1]
if len(_lowercase ) & 1:
clean += "X"
return clean
def __A ( _lowercase ):
'''simple docstring'''
_A = '''ABCDEFGHIKLMNOPQRSTUVWXYZ'''
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
_A = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(_lowercase )
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(_lowercase )
return table
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = prepare_input(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
ciphertext += table[rowa * 5 + (cola + 1) % 5]
ciphertext += table[rowa * 5 + (cola + 1) % 5]
elif cola == cola:
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
else: # rectangle
ciphertext += table[rowa * 5 + cola]
ciphertext += table[rowa * 5 + cola]
return ciphertext
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
plaintext += table[rowa * 5 + (cola - 1) % 5]
plaintext += table[rowa * 5 + (cola - 1) % 5]
elif cola == cola:
plaintext += table[((rowa - 1) % 5) * 5 + cola]
plaintext += table[((rowa - 1) % 5) * 5 + cola]
else: # rectangle
plaintext += table[rowa * 5 + cola]
plaintext += table[rowa * 5 + cola]
return plaintext
| 62 | 0 |
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging
__A = logging.get_logger(__name__)
__A = {
'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json',
# See all Marian models at https://huggingface.co/models?filter=marian
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "marian"
A_ = ["past_key_values"]
A_ = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
def __init__( self: Union[str, Any] , __A: Any=5_81_01 , __A: Optional[Any]=None , __A: List[str]=10_24 , __A: Any=12 , __A: Tuple=40_96 , __A: Union[str, Any]=16 , __A: Tuple=12 , __A: Optional[int]=40_96 , __A: List[Any]=16 , __A: Optional[Any]=0.0 , __A: Optional[Any]=0.0 , __A: Optional[int]=True , __A: str=True , __A: Tuple="gelu" , __A: str=10_24 , __A: str=0.1 , __A: Dict=0.0 , __A: List[str]=0.0 , __A: List[Any]=0.02 , __A: int=5_81_00 , __A: Tuple=False , __A: Optional[int]=5_81_00 , __A: int=0 , __A: Optional[int]=0 , __A: Optional[int]=True , **__A: Dict , ) -> Dict:
_A = vocab_size
_A = decoder_vocab_size or vocab_size
_A = max_position_embeddings
_A = d_model
_A = encoder_ffn_dim
_A = encoder_layers
_A = encoder_attention_heads
_A = decoder_ffn_dim
_A = decoder_layers
_A = decoder_attention_heads
_A = dropout
_A = attention_dropout
_A = activation_dropout
_A = activation_function
_A = init_std
_A = encoder_layerdrop
_A = decoder_layerdrop
_A = use_cache
_A = encoder_layers
_A = scale_embedding # scale factor will be sqrt(d_model) if True
_A = share_encoder_decoder_embeddings
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 , )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
def __A ( self: Any ) -> Mapping[str, Mapping[int, str]]:
if self.task in ["default", "seq2seq-lm"]:
_A = OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
] )
if self.use_past:
_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_(__A , direction='''inputs''' )
elif self.task == "causal-lm":
# TODO: figure this case out.
_A = OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
] )
if self.use_past:
_A ,_A = self.num_layers
for i in range(__A ):
_A = {0: '''batch''', 2: '''past_sequence + sequence'''}
_A = {0: '''batch''', 2: '''past_sequence + sequence'''}
else:
_A = OrderedDict(
[
('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}),
('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}),
] )
return common_inputs
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
def __A ( self: int ) -> Mapping[str, Mapping[int, str]]:
if self.task in ["default", "seq2seq-lm"]:
_A = super().outputs
else:
_A = super(__A , self ).outputs
if self.use_past:
_A ,_A = self.num_layers
for i in range(__A ):
_A = {0: '''batch''', 2: '''past_sequence + sequence'''}
_A = {0: '''batch''', 2: '''past_sequence + sequence'''}
return common_outputs
def __A ( self: Optional[Any] , __A: PreTrainedTokenizer , __A: int = -1 , __A: int = -1 , __A: bool = False , __A: Optional[TensorType] = None , ) -> Mapping[str, Any]:
_A = self._generate_dummy_inputs_for_encoder_and_decoder(
__A , __A , __A , __A , __A )
# Generate decoder inputs
_A = seq_length if not self.use_past else 1
_A = self._generate_dummy_inputs_for_encoder_and_decoder(
__A , __A , __A , __A , __A )
_A = {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
_A = dict(**__A , **__A )
if self.use_past:
if not is_torch_available():
raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
else:
import torch
_A ,_A = common_inputs['''input_ids'''].shape
_A = common_inputs['''decoder_input_ids'''].shape[1]
_A ,_A = self.num_attention_heads
_A = (
batch,
num_encoder_attention_heads,
encoder_seq_length,
self._config.hidden_size // num_encoder_attention_heads,
)
_A = decoder_seq_length + 3
_A = (
batch,
num_decoder_attention_heads,
decoder_past_length,
self._config.hidden_size // num_decoder_attention_heads,
)
_A = torch.cat(
[common_inputs['''decoder_attention_mask'''], torch.ones(__A , __A )] , dim=1 )
_A = []
# If the number of encoder and decoder layers are present in the model configuration, both are considered
_A ,_A = self.num_layers
_A = min(__A , __A )
_A = max(__A , __A ) - min_num_layers
_A = '''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder'''
for _ in range(__A ):
common_inputs["past_key_values"].append(
(
torch.zeros(__A ),
torch.zeros(__A ),
torch.zeros(__A ),
torch.zeros(__A ),
) )
# TODO: test this.
_A = encoder_shape if remaining_side_name == '''encoder''' else decoder_shape
for _ in range(__A , __A ):
common_inputs["past_key_values"].append((torch.zeros(__A ), torch.zeros(__A )) )
return common_inputs
def __A ( self: List[str] , __A: PreTrainedTokenizer , __A: int = -1 , __A: int = -1 , __A: bool = False , __A: Optional[TensorType] = None , ) -> Mapping[str, Any]:
_A = self._generate_dummy_inputs_for_encoder_and_decoder(
__A , __A , __A , __A , __A )
if self.use_past:
if not is_torch_available():
raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' )
else:
import torch
_A ,_A = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
_A = seqlen + 2
_A ,_A = self.num_layers
_A ,_A = self.num_attention_heads
_A = (
batch,
num_encoder_attention_heads,
past_key_values_length,
self._config.hidden_size // num_encoder_attention_heads,
)
_A = common_inputs['''attention_mask'''].dtype
_A = torch.cat(
[common_inputs['''attention_mask'''], torch.ones(__A , __A , dtype=__A )] , dim=1 )
_A = [
(torch.zeros(__A ), torch.zeros(__A )) for _ in range(__A )
]
return common_inputs
def __A ( self: int , __A: PreTrainedTokenizer , __A: int = -1 , __A: int = -1 , __A: bool = False , __A: Optional[TensorType] = None , ) -> Mapping[str, Any]:
# Copied from OnnxConfig.generate_dummy_inputs
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
_A = compute_effective_axis_dimension(
__A , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
_A = tokenizer.num_special_tokens_to_add(__A )
_A = compute_effective_axis_dimension(
__A , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__A )
# Generate dummy inputs according to compute batch and sequence
_A = [''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size
_A = dict(tokenizer(__A , return_tensors=__A ) )
return common_inputs
def __A ( self: Union[str, Any] , __A: PreTrainedTokenizer , __A: int = -1 , __A: int = -1 , __A: bool = False , __A: Optional[TensorType] = None , ) -> Mapping[str, Any]:
if self.task in ["default", "seq2seq-lm"]:
_A = self._generate_dummy_inputs_for_default_and_seqaseq_lm(
__A , batch_size=__A , seq_length=__A , is_pair=__A , framework=__A )
else:
_A = self._generate_dummy_inputs_for_causal_lm(
__A , batch_size=__A , seq_length=__A , is_pair=__A , framework=__A )
return common_inputs
def __A ( self: Dict , __A: Any , __A: Any , __A: Tuple , __A: Dict ) -> Union[str, Any]:
if self.task in ["default", "seq2seq-lm"]:
_A = super()._flatten_past_key_values_(__A , __A , __A , __A )
else:
_A = super(__A , self )._flatten_past_key_values_(
__A , __A , __A , __A )
@property
def __A ( self: Any ) -> float:
return 1e-4
| 709 |
import gc
import unittest
from transformers import CTRLConfig, 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, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Tuple , __A: Any , __A: List[Any]=14 , __A: Dict=7 , __A: List[str]=True , __A: Tuple=True , __A: Union[str, Any]=True , __A: List[Any]=True , __A: Optional[int]=True , __A: Tuple=99 , __A: Optional[Any]=32 , __A: List[str]=5 , __A: Dict=4 , __A: str=37 , __A: Dict="gelu" , __A: List[str]=0.1 , __A: str=0.1 , __A: Any=5_12 , __A: Union[str, Any]=16 , __A: List[Any]=2 , __A: Tuple=0.02 , __A: Tuple=3 , __A: Union[str, Any]=4 , __A: Any=None , ) -> Optional[Any]:
_A = parent
_A = batch_size
_A = seq_length
_A = is_training
_A = use_token_type_ids
_A = use_input_mask
_A = use_labels
_A = use_mc_token_ids
_A = vocab_size
_A = hidden_size
_A = num_hidden_layers
_A = num_attention_heads
_A = intermediate_size
_A = hidden_act
_A = hidden_dropout_prob
_A = attention_probs_dropout_prob
_A = max_position_embeddings
_A = type_vocab_size
_A = type_sequence_label_size
_A = initializer_range
_A = num_labels
_A = num_choices
_A = scope
_A = self.vocab_size - 1
def __A ( self: Optional[int] ) -> Union[str, Any]:
_A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_A = None
if self.use_input_mask:
_A = random_attention_mask([self.batch_size, self.seq_length] )
_A = None
if self.use_token_type_ids:
_A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_A = None
if self.use_mc_token_ids:
_A = ids_tensor([self.batch_size, self.num_choices] , self.seq_length )
_A = None
_A = None
_A = None
if self.use_labels:
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_A = ids_tensor([self.batch_size] , self.num_choices )
_A = self.get_config()
_A = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
token_type_ids,
mc_token_ids,
sequence_labels,
token_labels,
choice_labels,
)
def __A ( self: Optional[int] ) -> List[Any]:
return CTRLConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , )
def __A ( self: Union[str, Any] , __A: Union[str, Any] , __A: Dict , __A: Optional[int] , __A: List[str] , __A: List[str] , *__A: Optional[int] ) -> Optional[Any]:
_A = CTRLModel(config=__A )
model.to(__A )
model.eval()
model(__A , token_type_ids=__A , head_mask=__A )
model(__A , token_type_ids=__A )
_A = model(__A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(len(result.past_key_values ) , config.n_layer )
def __A ( self: Optional[Any] , __A: List[str] , __A: Dict , __A: List[Any] , __A: List[Any] , __A: Any , *__A: Any ) -> str:
_A = CTRLLMHeadModel(__A )
model.to(__A )
model.eval()
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __A ( self: Optional[int] ) -> Dict:
_A = self.prepare_config_and_inputs()
(
(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,
) = config_and_inputs
_A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}
return config, inputs_dict
def __A ( self: List[str] , __A: Dict , __A: Dict , __A: Tuple , __A: List[Any] , *__A: Optional[int] ) -> Any:
_A = self.num_labels
_A = CTRLForSequenceClassification(__A )
model.to(__A )
model.eval()
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
A_ = (CTRLLMHeadModel,) if is_torch_available() else ()
A_ = (
{
"feature-extraction": CTRLModel,
"text-classification": CTRLForSequenceClassification,
"text-generation": CTRLLMHeadModel,
"zero-shot": CTRLForSequenceClassification,
}
if is_torch_available()
else {}
)
A_ = True
A_ = False
A_ = False
def __A ( self: Any , __A: List[Any] , __A: int , __A: Optional[Any] , __A: Optional[int] , __A: List[Any] ) -> List[str]:
if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
# config could not be created.
return True
return False
def __A ( self: Any ) -> Union[str, Any]:
_A = CTRLModelTester(self )
_A = ConfigTester(self , config_class=__A , n_embd=37 )
def __A ( self: Optional[int] ) -> List[Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
def __A ( self: Dict ) -> Any:
self.config_tester.run_common_tests()
def __A ( self: str ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_ctrl_model(*__A )
def __A ( self: List[str] ) -> Any:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head_model(*__A )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: Optional[Any] ) -> int:
pass
@slow
def __A ( self: Tuple ) -> Dict:
for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_A = CTRLModel.from_pretrained(__A )
self.assertIsNotNone(__A )
@unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :)
def __A ( self: Any ) -> Union[str, Any]:
pass
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: int ) -> Union[str, Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
@slow
def __A ( self: Any ) -> Any:
_A = CTRLLMHeadModel.from_pretrained('''ctrl''' )
model.to(__A )
_A = torch.tensor(
[[1_18_59, 0, 16_11, 8]] , dtype=torch.long , device=__A ) # Legal the president is
_A = [
1_18_59,
0,
16_11,
8,
5,
1_50,
2_64_49,
2,
19,
3_48,
4_69,
3,
25_95,
48,
2_07_40,
24_65_33,
24_65_33,
19,
30,
5,
] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a
_A = model.generate(__A , do_sample=__A )
self.assertListEqual(output_ids[0].tolist() , __A )
| 62 | 0 |
def __A ( _lowercase = 1_00_00_00 ):
'''simple docstring'''
_A = 1
_A = 1
_A = {1: 1}
for inputa in range(2 , _lowercase ):
_A = 0
_A = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_A = (3 * number) + 1
counter += 1
if inputa not in counters:
_A = counter
if counter > pre_counter:
_A = inputa
_A = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 710 |
__A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
__A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = []
for neighbour in graph[vert]:
if not visited[neighbour]:
order += topology_sort(_lowercase , _lowercase , _lowercase )
order.append(_lowercase )
return order
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = [vert]
for neighbour in reversed_graph[vert]:
if not visited[neighbour]:
component += find_components(_lowercase , _lowercase , _lowercase )
return component
def __A ( _lowercase ):
'''simple docstring'''
_A = len(_lowercase ) * [False]
_A = {vert: [] for vert in range(len(_lowercase ) )}
for vert, neighbours in graph.items():
for neighbour in neighbours:
reversed_graph[neighbour].append(_lowercase )
_A = []
for i, was_visited in enumerate(_lowercase ):
if not was_visited:
order += topology_sort(_lowercase , _lowercase , _lowercase )
_A = []
_A = len(_lowercase ) * [False]
for i in range(len(_lowercase ) ):
_A = order[len(_lowercase ) - i - 1]
if not visited[vert]:
_A = find_components(_lowercase , _lowercase , _lowercase )
components_list.append(_lowercase )
return components_list
| 62 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'kssteven/ibert-roberta-base': 'https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json',
'kssteven/ibert-roberta-large': 'https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json',
'kssteven/ibert-roberta-large-mnli': (
'https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json'
),
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "ibert"
def __init__( self: Any , __A: Tuple=3_05_22 , __A: List[Any]=7_68 , __A: Tuple=12 , __A: Dict=12 , __A: List[str]=30_72 , __A: str="gelu" , __A: str=0.1 , __A: Tuple=0.1 , __A: Optional[Any]=5_12 , __A: List[str]=2 , __A: Any=0.02 , __A: int=1e-12 , __A: List[Any]=1 , __A: List[Any]=0 , __A: Any=2 , __A: Optional[Any]="absolute" , __A: Tuple=False , __A: List[Any]="none" , **__A: Any , ) -> List[str]:
super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
_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 = quant_mode
_A = force_dequant
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
def __A ( self: Optional[int] ) -> Mapping[str, Mapping[int, str]]:
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),
] )
| 711 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
global f # a global dp table for knapsack
if f[i][j] < 0:
if j < wt[i - 1]:
_A = mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase )
else:
_A = max(
mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase ) , mf_knapsack(i - 1 , _lowercase , _lowercase , j - wt[i - 1] ) + val[i - 1] , )
_A = val
return f[i][j]
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = [[0] * (w + 1) for _ in range(n + 1 )]
for i in range(1 , n + 1 ):
for w_ in range(1 , w + 1 ):
if wt[i - 1] <= w_:
_A = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] )
else:
_A = dp[i - 1][w_]
return dp[n][w_], dp
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if not (isinstance(_lowercase , (list, tuple) ) and isinstance(_lowercase , (list, tuple) )):
raise ValueError(
'''Both the weights and values vectors must be either lists or tuples''' )
_A = len(_lowercase )
if num_items != len(_lowercase ):
_A = (
'''The number of weights must be the same as the number of values.\n'''
f"""But got {num_items} weights and {len(_lowercase )} values"""
)
raise ValueError(_lowercase )
for i in range(_lowercase ):
if not isinstance(wt[i] , _lowercase ):
_A = (
'''All weights must be integers but got weight of '''
f"""type {type(wt[i] )} at index {i}"""
)
raise TypeError(_lowercase )
_A ,_A = knapsack(_lowercase , _lowercase , _lowercase , _lowercase )
_A = set()
_construct_solution(_lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
return optimal_val, example_optional_set
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if i > 0 and j > 0:
if dp[i - 1][j] == dp[i][j]:
_construct_solution(_lowercase , _lowercase , i - 1 , _lowercase , _lowercase )
else:
optimal_set.add(_lowercase )
_construct_solution(_lowercase , _lowercase , i - 1 , j - wt[i - 1] , _lowercase )
if __name__ == "__main__":
__A = [3, 2, 4, 4]
__A = [4, 3, 2, 3]
__A = 4
__A = 6
__A = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)]
__A , __A = knapsack(w, wt, val, n)
print(optimal_solution)
print(mf_knapsack(n, wt, val, w)) # switched the n and w
# testing the dynamic programming problem with example
# the optimal subset for the above example are items 3 and 4
__A , __A = knapsack_with_example_solution(w, wt, val)
assert optimal_solution == 8
assert optimal_subset == {3, 4}
print('optimal_value = ', optimal_solution)
print('An optimal subset corresponding to the optimal value', optimal_subset)
| 62 | 0 |
import argparse
import torch
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
'--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
)
# !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
parser.add_argument(
'--original_config_file',
default=None,
type=str,
help='The YAML config file corresponding to the original architecture.',
)
parser.add_argument(
'--num_in_channels',
default=None,
type=int,
help='The number of input channels. If `None` number of input channels will be automatically inferred.',
)
parser.add_argument(
'--scheduler_type',
default='pndm',
type=str,
help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']',
)
parser.add_argument(
'--pipeline_type',
default=None,
type=str,
help=(
'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\''
'. If `None` pipeline will be automatically inferred.'
),
)
parser.add_argument(
'--image_size',
default=None,
type=int,
help=(
'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
' Base. Use 768 for Stable Diffusion v2.'
),
)
parser.add_argument(
'--prediction_type',
default=None,
type=str,
help=(
'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable'
' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.'
),
)
parser.add_argument(
'--extract_ema',
action='store_true',
help=(
'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
),
)
parser.add_argument(
'--upcast_attention',
action='store_true',
help=(
'Whether the attention computation should always be upcasted. This is necessary when running stable'
' diffusion 2.1.'
),
)
parser.add_argument(
'--from_safetensors',
action='store_true',
help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
)
parser.add_argument(
'--to_safetensors',
action='store_true',
help='Whether to store pipeline in safetensors format or not.',
)
parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
parser.add_argument(
'--stable_unclip',
type=str,
default=None,
required=False,
help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.',
)
parser.add_argument(
'--stable_unclip_prior',
type=str,
default=None,
required=False,
help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.',
)
parser.add_argument(
'--clip_stats_path',
type=str,
help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.',
required=False,
)
parser.add_argument(
'--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.'
)
parser.add_argument('--half', action='store_true', help='Save weights in half precision.')
parser.add_argument(
'--vae_path',
type=str,
default=None,
required=False,
help='Set to a path, hub id to an already converted vae to not convert it again.',
)
__A = parser.parse_args()
__A = download_from_original_stable_diffusion_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
prediction_type=args.prediction_type,
model_type=args.pipeline_type,
extract_ema=args.extract_ema,
scheduler_type=args.scheduler_type,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
stable_unclip=args.stable_unclip,
stable_unclip_prior=args.stable_unclip_prior,
clip_stats_path=args.clip_stats_path,
controlnet=args.controlnet,
vae_path=args.vae_path,
)
if args.half:
pipe.to(torch_dtype=torch.floataa)
if args.controlnet:
# only save the controlnet model
pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
else:
pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
| 712 |
def __A ( _lowercase = 1_00_00_00 ):
'''simple docstring'''
_A = 1
_A = 1
_A = {1: 1}
for inputa in range(2 , _lowercase ):
_A = 0
_A = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_A = (3 * number) + 1
counter += 1
if inputa not in counters:
_A = counter
if counter > pre_counter:
_A = inputa
_A = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 62 | 0 |
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = AutoConfig.from_pretrained(_lowercase )
_A = FlaxAutoModelForSeqaSeqLM.from_config(config=_lowercase )
_A = checkpoints.load_tax_checkpoint(_lowercase )
_A = '''wi_0''' in tax_model['''target''']['''encoder''']['''layers_0''']['''mlp''']
if config.model_type == "t5":
_A = '''SelfAttention'''
if config.model_type == "longt5" and config.encoder_attention_type == "local":
_A = '''LocalSelfAttention'''
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
_A = '''TransientGlobalSelfAttention'''
else:
raise ValueError(
'''Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`'''
''' attribute with a value from [\'local\', \'transient-global].''' )
# Encoder
for layer_index in range(config.num_layers ):
_A = f"""layers_{str(_lowercase )}"""
# Self-Attention
_A = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''key''']['''kernel''']
_A = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''out''']['''kernel''']
_A = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''query''']['''kernel''']
_A = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''value''']['''kernel''']
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
_A = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''T5LayerNorm_0''']['''scale''']
# Layer Normalization
_A = tax_model['''target''']['''encoder'''][layer_name]['''pre_attention_layer_norm''']['''scale''']
if split_mlp_wi:
_A = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel''']
_A = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel''']
else:
_A = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi''']['''kernel''']
_A = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wo''']['''kernel''']
# Layer Normalization
_A = tax_model['''target''']['''encoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale''']
# Assigning
_A = flax_model.params['''encoder''']['''block'''][str(_lowercase )]['''layer''']
_A = tax_attention_key
_A = tax_attention_out
_A = tax_attention_query
_A = tax_attention_value
_A = tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
_A = tax_global_layer_norm
if split_mlp_wi:
_A = tax_mlp_wi_a
_A = tax_mlp_wi_a
else:
_A = tax_mlp_wi
_A = tax_mlp_wo
_A = tax_mlp_layer_norm
_A = flax_model_encoder_layer_block
# Only for layer 0:
_A = tax_model['''target''']['''encoder''']['''relpos_bias''']['''rel_embedding'''].T
_A = tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
_A = tax_model['''target''']['''encoder''']['''side_relpos_bias''']['''rel_embedding'''].T
_A = tax_encoder_global_rel_embedding
# Assigning
_A = tax_model['''target''']['''encoder''']['''encoder_norm''']['''scale''']
_A = tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
_A = f"""layers_{str(_lowercase )}"""
# Self-Attention
_A = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''key''']['''kernel''']
_A = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''out''']['''kernel''']
_A = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''query''']['''kernel''']
_A = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''value''']['''kernel''']
# Layer Normalization
_A = tax_model['''target''']['''decoder'''][layer_name]['''pre_self_attention_layer_norm'''][
'''scale'''
]
# Encoder-Decoder-Attention
_A = tax_model['''target''']['''decoder'''][layer_name]['''encoder_decoder_attention''']
_A = tax_enc_dec_attention_module['''key''']['''kernel''']
_A = tax_enc_dec_attention_module['''out''']['''kernel''']
_A = tax_enc_dec_attention_module['''query''']['''kernel''']
_A = tax_enc_dec_attention_module['''value''']['''kernel''']
# Layer Normalization
_A = tax_model['''target''']['''decoder'''][layer_name]['''pre_cross_attention_layer_norm''']['''scale''']
# MLP
if split_mlp_wi:
_A = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel''']
_A = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel''']
else:
_A = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi''']['''kernel''']
_A = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wo''']['''kernel''']
# Layer Normalization
_A = tax_model['''target''']['''decoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale''']
# Assigning
_A = flax_model.params['''decoder''']['''block'''][str(_lowercase )]['''layer''']
_A = tax_attention_key
_A = tax_attention_out
_A = tax_attention_query
_A = tax_attention_value
_A = tax_pre_attention_layer_norm
_A = tax_enc_dec_attention_key
_A = tax_enc_dec_attention_out
_A = tax_enc_dec_attention_query
_A = tax_enc_dec_attention_value
_A = tax_cross_layer_norm
if split_mlp_wi:
_A = tax_mlp_wi_a
_A = tax_mlp_wi_a
else:
_A = tax_mlp_wi
_A = tax_mlp_wo
_A = txa_mlp_layer_norm
_A = flax_model_decoder_layer_block
# Decoder Normalization
_A = tax_model['''target''']['''decoder''']['''decoder_norm''']['''scale''']
_A = txa_decoder_norm
# Only for layer 0:
_A = tax_model['''target''']['''decoder''']['''relpos_bias''']['''rel_embedding'''].T
_A = tax_decoder_rel_embedding
# Token Embeddings
_A = tax_model['''target''']['''token_embedder''']['''embedding''']
_A = txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
_A = tax_model['''target''']['''decoder''']['''logits_dense''']['''kernel''']
flax_model.save_pretrained(_lowercase )
print('''T5X Model was sucessfully converted!''' )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.'
)
parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.')
parser.add_argument(
'--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.'
)
__A = parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 713 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = word.split()
def justify(_lowercase , _lowercase , _lowercase ) -> str:
_A = max_width - width
_A = len(_lowercase )
if len(_lowercase ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_A = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_A = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_A = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_lowercase ):
num_spaces_between_words_list[i] += 1
_A = []
for i in range(_lowercase ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * ''' ''' )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_lowercase )
_A = []
_A = []
_A = 0
for word in words:
if width + len(_lowercase ) + len(_lowercase ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_lowercase )
width += len(_lowercase )
else:
# justify the line and add it to result
answer.append(justify(_lowercase , _lowercase , _lowercase ) )
# reset new line and new width
_A ,_A = [word], len(_lowercase )
_A = max_width - width - len(_lowercase )
answer.append(''' '''.join(_lowercase ) + (remaining_spaces + 1) * ''' ''' )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 62 | 0 |
import unittest
import numpy as np
import requests
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
__A = False
if is_vision_available():
from PIL import Image
from transformers import PixaStructImageProcessor
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __init__( self: Tuple , __A: str , __A: Dict=7 , __A: Tuple=3 , __A: Dict=18 , __A: Dict=30 , __A: Tuple=4_00 , __A: Optional[int]=None , __A: List[Any]=True , __A: int=True , __A: Optional[int]=None , ) -> str:
_A = size if size is not None else {'''height''': 20, '''width''': 20}
_A = parent
_A = batch_size
_A = num_channels
_A = image_size
_A = min_resolution
_A = max_resolution
_A = size
_A = do_normalize
_A = do_convert_rgb
_A = [5_12, 10_24, 20_48, 40_96]
_A = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
def __A ( self: Tuple ) -> Optional[Any]:
return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}
def __A ( self: str ) -> List[str]:
_A = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
_A = Image.open(requests.get(__A , stream=__A ).raw ).convert('''RGB''' )
return raw_image
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." , )
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = PixaStructImageProcessor if is_vision_available() else None
def __A ( self: Optional[int] ) -> Any:
_A = PixaStructImageProcessingTester(self )
@property
def __A ( self: List[Any] ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self: Optional[int] ) -> Union[str, Any]:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , '''do_normalize''' ) )
self.assertTrue(hasattr(__A , '''do_convert_rgb''' ) )
def __A ( self: Any ) -> Union[str, Any]:
_A = self.image_processor_tester.prepare_dummy_image()
_A = self.image_processing_class(**self.image_processor_dict )
_A = 20_48
_A = image_processor(__A , return_tensors='''pt''' , max_patches=__A )
self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0_606 ) , atol=1e-3 , rtol=1e-3 ) )
def __A ( self: Optional[int] ) -> List[str]:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
__A , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def __A ( self: Any ) -> Tuple:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
_A = True
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
with self.assertRaises(__A ):
_A = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__A ).flattened_patches
_A = '''Hello'''
_A = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__A , header_text=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
__A , return_tensors='''pt''' , max_patches=__A , header_text=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def __A ( self: Optional[int] ) -> Any:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A )
for image in image_inputs:
self.assertIsInstance(__A , np.ndarray )
_A = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
__A , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def __A ( self: Tuple ) -> str:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A )
for image in image_inputs:
self.assertIsInstance(__A , torch.Tensor )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
__A , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." , )
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = PixaStructImageProcessor if is_vision_available() else None
def __A ( self: Optional[int] ) -> List[str]:
_A = PixaStructImageProcessingTester(self , num_channels=4 )
_A = 3
@property
def __A ( self: List[Any] ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self: str ) -> Dict:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , '''do_normalize''' ) )
self.assertTrue(hasattr(__A , '''do_convert_rgb''' ) )
def __A ( self: List[Any] ) -> str:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
* (self.image_processor_tester.num_channels - 1)
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
__A , return_tensors='''pt''' , max_patches=__A ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
| 714 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(_lowercase , '''utf-8''' )
with zstd.open(_lowercase , '''wb''' ) as f:
f.write(_lowercase )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , _lowercase ) , '''w''' ) as f:
f.write(_lowercase )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=_lowercase , extract_compressed_file=_lowercase )
_A = cached_path(_lowercase , download_config=_lowercase )
with open(_lowercase ) as f:
_A = f.read()
with open(_lowercase ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , _lowercase )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(_lowercase ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=_lowercase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowercase )
)
_A = cached_path(_lowercase , download_config=_lowercase )
assert Path(_lowercase ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(_lowercase ).resolve() )
assert cached_path(_lowercase ) == text_file
# relative path
_A = str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowercase ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(_lowercase ):
cached_path(_lowercase )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(_lowercase ):
cached_path(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(_lowercase ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( ):
'''simple docstring'''
with pytest.raises(_lowercase ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
http_get('''https://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
ftp_get('''ftp://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
fsspec_get('''s3://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
fsspec_head('''s3://huggingface.co''' )
| 62 | 0 |
'''simple docstring'''
from typing import Optional
import numpy as np
import torch
from torch import nn
from transformers import GPTaConfig, GPTaLMHeadModel
from transformers.modeling_utils import ModuleUtilsMixin
from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ):
"""simple docstring"""
A_ = [R"h\.\d+\.attn\.bias", R"h\.\d+\.attn\.masked_bias"]
@register_to_config
def __init__( self: int , __A: int , __A: int , __A: Optional[int] = None , __A: int = 5_02_57 , __A: int = 10_24 , __A: int = 7_68 , __A: int = 12 , __A: int = 12 , __A: Optional[int] = None , __A: str = "gelu_new" , __A: float = 0.1 , __A: float = 0.1 , __A: float = 0.1 , __A: float = 1e-5 , __A: float = 0.02 , __A: bool = True , __A: bool = True , __A: bool = False , __A: bool = False , ) -> Union[str, Any]:
super().__init__()
_A = prefix_length
if prefix_inner_dim != n_embd and prefix_hidden_dim is None:
raise ValueError(
f"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and"""
f""" `n_embd`: {n_embd} are not equal.""" )
_A = prefix_inner_dim
_A = prefix_hidden_dim
_A = (
nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim )
if self.prefix_hidden_dim is not None
else nn.Identity()
)
_A = (
nn.Linear(self.prefix_hidden_dim , __A ) if self.prefix_hidden_dim is not None else nn.Identity()
)
_A = GPTaConfig(
vocab_size=__A , n_positions=__A , n_embd=__A , n_layer=__A , n_head=__A , n_inner=__A , activation_function=__A , resid_pdrop=__A , embd_pdrop=__A , attn_pdrop=__A , layer_norm_epsilon=__A , initializer_range=__A , scale_attn_weights=__A , use_cache=__A , scale_attn_by_inverse_layer_idx=__A , reorder_and_upcast_attn=__A , )
_A = GPTaLMHeadModel(__A )
def __A ( self: Any , __A: torch.Tensor , __A: torch.Tensor , __A: Optional[torch.Tensor] = None , __A: Optional[torch.Tensor] = None , ) -> List[Any]:
_A = self.transformer.transformer.wte(__A )
_A = self.encode_prefix(__A )
_A = self.decode_prefix(__A )
_A = torch.cat((prefix_embeds, embedding_text) , dim=1 )
if labels is not None:
_A = self.get_dummy_token(input_ids.shape[0] , input_ids.device )
_A = torch.cat((dummy_token, input_ids) , dim=1 )
_A = self.transformer(inputs_embeds=__A , labels=__A , attention_mask=__A )
if self.prefix_hidden_dim is not None:
return out, hidden
else:
return out
def __A ( self: Union[str, Any] , __A: int , __A: torch.device ) -> torch.Tensor:
return torch.zeros(__A , self.prefix_length , dtype=torch.intaa , device=__A )
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Any:
return self.encode_prefix(__A )
@torch.no_grad()
def __A ( self: Any , __A: Dict , __A: Tuple , __A: str ) -> Tuple:
_A = torch.split(__A , 1 , dim=0 )
_A = []
_A = []
for feature in features:
_A = self.decode_prefix(feature.to(__A ) ) # back to the clip feature
# Only support beam search for now
_A ,_A = self.generate_beam(
input_embeds=__A , device=__A , eos_token_id=__A )
generated_tokens.append(output_tokens[0] )
generated_seq_lengths.append(seq_lengths[0] )
_A = torch.stack(__A )
_A = torch.stack(__A )
return generated_tokens, generated_seq_lengths
@torch.no_grad()
def __A ( self: str , __A: str=None , __A: Any=None , __A: Dict=None , __A: int = 5 , __A: int = 67 , __A: float = 1.0 , __A: Optional[int] = None , ) -> Optional[Any]:
_A = eos_token_id
_A = None
_A = None
_A = torch.ones(__A , device=__A , dtype=torch.int )
_A = torch.zeros(__A , device=__A , dtype=torch.bool )
if input_embeds is not None:
_A = input_embeds
else:
_A = self.transformer.transformer.wte(__A )
for i in range(__A ):
_A = self.transformer(inputs_embeds=__A )
_A = outputs.logits
_A = logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
_A = logits.softmax(-1 ).log()
if scores is None:
_A ,_A = logits.topk(__A , -1 )
_A = generated.expand(__A , *generated.shape[1:] )
_A ,_A = next_tokens.permute(1 , 0 ), scores.squeeze(0 )
if tokens is None:
_A = next_tokens
else:
_A = tokens.expand(__A , *tokens.shape[1:] )
_A = torch.cat((tokens, next_tokens) , dim=1 )
else:
_A = -float(np.inf )
_A = 0
_A = scores[:, None] + logits
seq_lengths[~is_stopped] += 1
_A = scores_sum / seq_lengths[:, None]
_A ,_A = scores_sum_average.view(-1 ).topk(__A , -1 )
_A = next_tokens // scores_sum.shape[1]
_A = seq_lengths[next_tokens_source]
_A = next_tokens % scores_sum.shape[1]
_A = next_tokens.unsqueeze(1 )
_A = tokens[next_tokens_source]
_A = torch.cat((tokens, next_tokens) , dim=1 )
_A = generated[next_tokens_source]
_A = scores_sum_average * seq_lengths
_A = is_stopped[next_tokens_source]
_A = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 )
_A = torch.cat((generated, next_token_embed) , dim=1 )
_A = is_stopped + next_tokens.eq(__A ).squeeze()
if is_stopped.all():
break
_A = scores / seq_lengths
_A = scores.argsort(descending=__A )
# tokens tensors are already padded to max_seq_length
_A = [tokens[i] for i in order]
_A = torch.stack(__A , dim=0 )
_A = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype )
return output_texts, seq_lengths
| 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 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool
if TYPE_CHECKING:
from PIL import Image
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "Salesforce/blip-image-captioning-base"
A_ = (
"This is a tool that generates a description of an image. It takes an input named `image` which should be the "
"image to caption, and returns a text that contains the description in English."
)
A_ = "image_captioner"
A_ = AutoModelForVisionaSeq
A_ = ["image"]
A_ = ["text"]
def __init__( self: str , *__A: str , **__A: Optional[Any] ) -> List[Any]:
requires_backends(self , ['''vision'''] )
super().__init__(*__A , **__A )
def __A ( self: Union[str, Any] , __A: "Image" ) -> int:
return self.pre_processor(images=__A , return_tensors='''pt''' )
def __A ( self: List[str] , __A: List[Any] ) -> Dict:
return self.model.generate(**__A )
def __A ( self: List[Any] , __A: Optional[int] ) -> List[str]:
return self.pre_processor.batch_decode(__A , skip_special_tokens=__A )[0].strip()
| 716 |
import flax.linen as nn
import jax
import jax.numpy as jnp
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: Tuple ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Dict , __A: Dict ) -> Tuple:
_A ,_A ,_A ,_A = hidden_states.shape
_A = jax.image.resize(
__A , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , )
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: List[str] ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Union[str, Any] , __A: List[Any] ) -> Union[str, Any]:
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = None
A_ = 0.0
A_ = None
A_ = jnp.floataa
def __A ( self: Dict ) -> Dict:
_A = self.in_channels if self.out_channels is None else self.out_channels
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = nn.Dense(__A , dtype=self.dtype )
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Dropout(self.dropout_prob )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
_A = None
if use_nin_shortcut:
_A = nn.Conv(
__A , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , )
def __call__( self: Dict , __A: List[Any] , __A: List[Any] , __A: Any=True ) -> List[Any]:
_A = hidden_states
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.conva(__A )
_A = self.time_emb_proj(nn.swish(__A ) )
_A = jnp.expand_dims(jnp.expand_dims(__A , 1 ) , 1 )
_A = hidden_states + temb
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.dropout(__A , __A )
_A = self.conva(__A )
if self.conv_shortcut is not None:
_A = self.conv_shortcut(__A )
return hidden_states + residual
| 62 | 0 |
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 SCREAMING_SNAKE_CASE ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self: List[Any] , __A: Dict[str, int] , __A: List[str] , __A: int = None , __A: int = None ) -> Any:
super().__init__()
_A = pad_token_id
_A = max_length
_A = vocab
_A = merges
_A = BytePairTokenizer(__A , __A , sequence_length=__A )
@classmethod
def __A ( cls: int , __A: GPTaTokenizer , *__A: Any , **__A: Optional[int] ) -> int:
_A = [''' '''.join(__A ) for m in tokenizer.bpe_ranks.keys()]
_A = tokenizer.get_vocab()
return cls(__A , __A , *__A , **__A )
@classmethod
def __A ( cls: Optional[int] , __A: Union[str, os.PathLike] , *__A: str , **__A: Tuple ) -> Optional[Any]:
_A = GPTaTokenizer.from_pretrained(__A , *__A , **__A )
return cls.from_tokenizer(__A , *__A , **__A )
@classmethod
def __A ( cls: int , __A: Tuple ) -> Tuple:
return cls(**__A )
def __A ( self: str ) -> List[Any]:
return {
"vocab": self.vocab,
"merges": self.merges,
"max_length": self.max_length,
"pad_token_id": self.pad_token_id,
}
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: int = None ) -> Dict:
_A = self.tf_tokenizer(__A )
_A = tf.ones_like(__A )
if self.pad_token_id is not None:
# pad the tokens up to max length
_A = max_length if max_length is not None else self.max_length
if max_length is not None:
_A ,_A = pad_model_inputs(
__A , max_seq_length=__A , pad_value=self.pad_token_id )
return {"attention_mask": attention_mask, "input_ids": input_ids}
| 717 |
def __A ( _lowercase ):
'''simple docstring'''
_A = [0] * len(_lowercase )
_A = []
_A = []
_A = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(_lowercase ) ):
if indegree[i] == 0:
queue.append(_lowercase )
while queue:
_A = queue.pop(0 )
cnt += 1
topo.append(_lowercase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(_lowercase )
if cnt != len(_lowercase ):
print('''Cycle exists''' )
else:
print(_lowercase )
# Adjacency List of Graph
__A = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 62 | 0 |
import os
import pickle
import unittest
from transformers import AutoTokenizer
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.models.bert_japanese.tokenization_bert_japanese import (
VOCAB_FILES_NAMES,
BertJapaneseTokenizer,
CharacterTokenizer,
JumanppTokenizer,
MecabTokenizer,
SudachiTokenizer,
WordpieceTokenizer,
)
from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi
from ...test_tokenization_common import TokenizerTesterMixin
@custom_tokenizers
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = BertJapaneseTokenizer
A_ = False
A_ = True
def __A ( self: int ) -> int:
super().setUp()
_A = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''こんにちは''',
'''こん''',
'''にちは''',
'''ばんは''',
'''##こん''',
'''##にちは''',
'''##ばんは''',
'''世界''',
'''##世界''',
'''、''',
'''##、''',
'''。''',
'''##。''',
]
_A = 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] ) )
def __A ( self: Dict , __A: List[Any] ) -> List[str]:
_A = '''こんにちは、世界。 \nこんばんは、世界。'''
_A = '''こんにちは 、 世界 。 こんばんは 、 世界 。'''
return input_text, output_text
def __A ( self: List[str] , __A: str ) -> Dict:
_A ,_A = self.get_input_output_texts(__A )
_A = tokenizer.encode(__A , add_special_tokens=__A )
_A = tokenizer.decode(__A , clean_up_tokenization_spaces=__A )
return text, ids
def __A ( self: Union[str, Any] ) -> List[str]:
pass # TODO add if relevant
def __A ( self: List[str] ) -> List[str]:
pass # TODO add if relevant
def __A ( self: str ) -> List[Any]:
pass # TODO add if relevant
def __A ( self: int ) -> Optional[Any]:
_A = self.tokenizer_class(self.vocab_file )
_A = tokenizer.tokenize('''こんにちは、世界。\nこんばんは、世界。''' )
self.assertListEqual(__A , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
def __A ( self: Tuple ) -> Union[str, Any]:
_A = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''mecab''' )
self.assertIsNotNone(__A )
_A = '''こんにちは、世界。\nこんばんは、世界。'''
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
_A = os.path.join(self.tmpdirname , '''tokenizer.bin''' )
with open(__A , '''wb''' ) as handle:
pickle.dump(__A , __A )
with open(__A , '''rb''' ) as handle:
_A = pickle.load(__A )
_A = tokenizer_new.tokenize(__A )
self.assertListEqual(__A , __A )
def __A ( self: Any ) -> List[str]:
_A = MecabTokenizer(mecab_dic='''ipadic''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def __A ( self: Optional[int] ) -> Union[str, Any]:
try:
_A = MecabTokenizer(mecab_dic='''unidic_lite''' )
except ModuleNotFoundError:
return
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def __A ( self: int ) -> Any:
try:
_A = MecabTokenizer(mecab_dic='''unidic''' )
except ModuleNotFoundError:
return
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def __A ( self: Optional[int] ) -> int:
_A = MecabTokenizer(do_lower_case=__A , mecab_dic='''ipadic''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iphone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def __A ( self: Optional[Any] ) -> Any:
try:
_A = MecabTokenizer(
do_lower_case=__A , normalize_text=__A , mecab_option='''-d /usr/local/lib/mecab/dic/jumandic''' )
except RuntimeError:
# if dict doesn't exist in the system, previous code raises this error.
return
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
def __A ( self: List[Any] ) -> List[Any]:
_A = MecabTokenizer(normalize_text=__A , mecab_dic='''ipadic''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。'''] , )
@require_sudachi
def __A ( self: int ) -> Any:
_A = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''sudachi''' )
self.assertIsNotNone(__A )
_A = '''こんにちは、世界。\nこんばんは、世界。'''
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
_A = os.path.join(self.tmpdirname , '''tokenizer.bin''' )
with open(__A , '''wb''' ) as handle:
pickle.dump(__A , __A )
with open(__A , '''rb''' ) as handle:
_A = pickle.load(__A )
_A = tokenizer_new.tokenize(__A )
self.assertListEqual(__A , __A )
@require_sudachi
def __A ( self: Union[str, Any] ) -> Dict:
_A = SudachiTokenizer(sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , )
@require_sudachi
def __A ( self: Optional[Any] ) -> Union[str, Any]:
_A = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''A''' )
self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国''', '''人''', '''参政''', '''権'''] )
@require_sudachi
def __A ( self: str ) -> Optional[int]:
_A = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''B''' )
self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人''', '''参政権'''] )
@require_sudachi
def __A ( self: Tuple ) -> Any:
_A = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''C''' )
self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人参政権'''] )
@require_sudachi
def __A ( self: Optional[int] ) -> int:
_A = SudachiTokenizer(do_lower_case=__A , sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , )
@require_sudachi
def __A ( self: Tuple ) -> List[Any]:
_A = SudachiTokenizer(normalize_text=__A , sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', '''\u3000''', '''。''', ''' ''', ''' '''] , )
@require_sudachi
def __A ( self: Optional[int] ) -> List[Any]:
_A = SudachiTokenizer(trim_whitespace=__A , sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
@require_jumanpp
def __A ( self: str ) -> Optional[int]:
_A = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''jumanpp''' )
self.assertIsNotNone(__A )
_A = '''こんにちは、世界。\nこんばんは、世界。'''
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
_A = os.path.join(self.tmpdirname , '''tokenizer.bin''' )
with open(__A , '''wb''' ) as handle:
pickle.dump(__A , __A )
with open(__A , '''rb''' ) as handle:
_A = pickle.load(__A )
_A = tokenizer_new.tokenize(__A )
self.assertListEqual(__A , __A )
@require_jumanpp
def __A ( self: List[str] ) -> Optional[Any]:
_A = JumanppTokenizer()
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
@require_jumanpp
def __A ( self: Optional[Any] ) -> Dict:
_A = JumanppTokenizer(do_lower_case=__A )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
@require_jumanpp
def __A ( self: List[Any] ) -> Optional[Any]:
_A = JumanppTokenizer(normalize_text=__A )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''ア''', '''ッ''', '''フ''', '''゚''', '''ル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
@require_jumanpp
def __A ( self: str ) -> Union[str, Any]:
_A = JumanppTokenizer(trim_whitespace=__A )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''。'''] , )
@require_jumanpp
def __A ( self: Optional[int] ) -> Union[str, Any]:
_A = JumanppTokenizer()
self.assertListEqual(
tokenizer.tokenize('''ありがとうございますm(_ _)m見つけるのが大変です。''' ) , ['''ありがとう''', '''ございます''', '''m(_ _)m''', '''見つける''', '''の''', '''が''', '''大変です''', '''。'''] , )
def __A ( self: Optional[Any] ) -> Union[str, Any]:
_A = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは''']
_A = {}
for i, token in enumerate(__A ):
_A = i
_A = WordpieceTokenizer(vocab=__A , unk_token='''[UNK]''' )
self.assertListEqual(tokenizer.tokenize('''''' ) , [] )
self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こんにちは'''] )
self.assertListEqual(tokenizer.tokenize('''こんばんは''' ) , ['''こん''', '''##ばんは'''] )
self.assertListEqual(tokenizer.tokenize('''こんばんは こんばんにちは こんにちは''' ) , ['''こん''', '''##ばんは''', '''[UNK]''', '''こんにちは'''] )
def __A ( self: Union[str, Any] ) -> str:
_A = BertJapaneseTokenizer.from_pretrained('''nlp-waseda/roberta-base-japanese-with-auto-jumanpp''' )
_A = tokenizer.subword_tokenizer
_A = subword_tokenizer.tokenize('''国境 の 長い トンネル を 抜ける と 雪国 であった 。''' )
self.assertListEqual(__A , ['''▁国境''', '''▁の''', '''▁長い''', '''▁トンネル''', '''▁を''', '''▁抜ける''', '''▁と''', '''▁雪''', '''国''', '''▁であった''', '''▁。'''] )
_A = subword_tokenizer.tokenize('''こんばんは こんばん にち は こんにちは''' )
self.assertListEqual(__A , ['''▁こん''', '''ばん''', '''は''', '''▁こん''', '''ばん''', '''▁に''', '''ち''', '''▁は''', '''▁こんにちは'''] )
def __A ( self: List[str] ) -> Union[str, Any]:
_A = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese''' )
_A = tokenizer.encode('''ありがとう。''' , add_special_tokens=__A )
_A = tokenizer.encode('''どういたしまして。''' , add_special_tokens=__A )
_A = tokenizer.build_inputs_with_special_tokens(__A )
_A = tokenizer.build_inputs_with_special_tokens(__A , __A )
# 2 is for "[CLS]", 3 is for "[SEP]"
assert encoded_sentence == [2] + text + [3]
assert encoded_pair == [2] + text + [3] + text_a + [3]
@custom_tokenizers
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = BertJapaneseTokenizer
A_ = False
def __A ( self: Optional[Any] ) -> Union[str, Any]:
super().setUp()
_A = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。''']
_A = 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] ) )
def __A ( self: Optional[Any] , **__A: str ) -> Dict:
return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='''character''' , **__A )
def __A ( self: List[str] , __A: Union[str, Any] ) -> Optional[int]:
_A = '''こんにちは、世界。 \nこんばんは、世界。'''
_A = '''こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。'''
return input_text, output_text
def __A ( self: int ) -> List[str]:
pass # TODO add if relevant
def __A ( self: Dict ) -> Optional[int]:
pass # TODO add if relevant
def __A ( self: List[Any] ) -> Optional[int]:
pass # TODO add if relevant
def __A ( self: Optional[int] ) -> List[str]:
_A = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='''character''' )
_A = tokenizer.tokenize('''こんにちは、世界。 \nこんばんは、世界。''' )
self.assertListEqual(
__A , ['''こ''', '''ん''', '''に''', '''ち''', '''は''', '''、''', '''世''', '''界''', '''。''', '''こ''', '''ん''', '''ば''', '''ん''', '''は''', '''、''', '''世''', '''界''', '''。'''] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__A ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] )
def __A ( self: Tuple ) -> Any:
_A = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。''']
_A = {}
for i, token in enumerate(__A ):
_A = i
_A = CharacterTokenizer(vocab=__A , unk_token='''[UNK]''' )
self.assertListEqual(tokenizer.tokenize('''''' ) , [] )
self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''は'''] )
self.assertListEqual(tokenizer.tokenize('''こんにちほ''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''[UNK]'''] )
def __A ( self: Optional[Any] ) -> Dict:
_A = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese-char''' )
_A = tokenizer.encode('''ありがとう。''' , add_special_tokens=__A )
_A = tokenizer.encode('''どういたしまして。''' , add_special_tokens=__A )
_A = tokenizer.build_inputs_with_special_tokens(__A )
_A = tokenizer.build_inputs_with_special_tokens(__A , __A )
# 2 is for "[CLS]", 3 is for "[SEP]"
assert encoded_sentence == [2] + text + [3]
assert encoded_pair == [2] + text + [3] + text_a + [3]
@custom_tokenizers
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Union[str, Any] ) -> List[Any]:
_A = '''cl-tohoku/bert-base-japanese'''
_A = AutoTokenizer.from_pretrained(__A )
self.assertIsInstance(__A , __A )
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Dict ) -> List[Any]:
_A = '''cl-tohoku/bert-base-japanese'''
with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm:
BertTokenizer.from_pretrained(__A )
self.assertTrue(
cm.records[0].message.startswith(
'''The tokenizer class you load from this checkpoint is not the same type as the class this function'''
''' is called from.''' ) )
_A = '''bert-base-cased'''
with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm:
BertJapaneseTokenizer.from_pretrained(__A )
self.assertTrue(
cm.records[0].message.startswith(
'''The tokenizer class you load from this checkpoint is not the same type as the class this function'''
''' is called from.''' ) )
| 718 |
import math
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 SchedulerMixin, SchedulerOutput
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = 1
@register_to_config
def __init__( self: Any , __A: int = 10_00 , __A: Optional[Union[np.ndarray, List[float]]] = None ) -> List[str]:
# set `betas`, `alphas`, `timesteps`
self.set_timesteps(__A )
# standard deviation of the initial noise distribution
_A = 1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
_A = 4
# running values
_A = []
def __A ( self: str , __A: int , __A: Union[str, torch.device] = None ) -> int:
_A = num_inference_steps
_A = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
_A = torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
_A = torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
_A = torch.sin(steps * math.pi / 2 ) ** 2
_A = (1.0 - self.betas**2) ** 0.5
_A = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
_A = timesteps.to(__A )
_A = []
def __A ( self: Tuple , __A: torch.FloatTensor , __A: int , __A: torch.FloatTensor , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
_A = (self.timesteps == timestep).nonzero().item()
_A = timestep_index + 1
_A = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(__A )
if len(self.ets ) == 1:
_A = self.ets[-1]
elif len(self.ets ) == 2:
_A = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
_A = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
_A = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
_A = self._get_prev_sample(__A , __A , __A , __A )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Optional[int] , __A: torch.FloatTensor , *__A: Tuple , **__A: List[Any] ) -> torch.FloatTensor:
return sample
def __A ( self: List[str] , __A: Optional[Any] , __A: Optional[Any] , __A: Any , __A: List[Any] ) -> List[Any]:
_A = self.alphas[timestep_index]
_A = self.betas[timestep_index]
_A = self.alphas[prev_timestep_index]
_A = self.betas[prev_timestep_index]
_A = (sample - sigma * ets) / max(__A , 1e-8 )
_A = next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self: List[str] ) -> Dict:
return self.config.num_train_timesteps
| 62 | 0 |
import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.utils import write_basic_config
from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available
logging.basicConfig(level=logging.DEBUG)
__A = logging.getLogger()
def __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser()
parser.add_argument('''-f''' )
_A = parser.parse_args()
return args.f
def __A ( _lowercase ):
'''simple docstring'''
_A = {}
_A = os.path.join(_lowercase , '''all_results.json''' )
if os.path.exists(_lowercase ):
with open(_lowercase , '''r''' ) as f:
_A = json.load(_lowercase )
else:
raise ValueError(f"""can't find {path}""" )
return results
def __A ( ):
'''simple docstring'''
_A = torch.cuda.is_available() and torch_device == '''cuda'''
return is_using_cuda and is_apex_available()
__A = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@classmethod
def __A ( cls: List[Any] ) -> List[Any]:
# Write Accelerate config, will pick up on CPU, GPU, and multi-GPU
_A = tempfile.mkdtemp()
_A = os.path.join(cls.tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
_A = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def __A ( cls: List[str] ) -> Optional[Any]:
shutil.rmtree(cls.tmpdir )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: Optional[int] ) -> List[Any]:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--seed=42
--checkpointing_steps epoch
--with_tracking
""".split()
if is_cuda_and_apex_available():
testargs.append('''--fp16''' )
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''glue_no_trainer''' ) ) )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: int ) -> List[str]:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py
--model_name_or_path distilgpt2
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--block_size 128
--per_device_train_batch_size 5
--per_device_eval_batch_size 5
--num_train_epochs 2
--output_dir {tmp_dir}
--checkpointing_steps epoch
--with_tracking
""".split()
if torch.cuda.device_count() > 1:
# Skipping because there are not enough batches to train the model + would need a drop_last to work.
return
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertLess(result['''perplexity'''] , 1_00 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''clm_no_trainer''' ) ) )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: int ) -> Union[str, Any]:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py
--model_name_or_path distilroberta-base
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--num_train_epochs=1
--checkpointing_steps epoch
--with_tracking
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertLess(result['''perplexity'''] , 42 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''mlm_no_trainer''' ) ) )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: Optional[int] ) -> List[str]:
# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
_A = 7 if get_gpu_count() > 1 else 2
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py
--model_name_or_path bert-base-uncased
--train_file tests/fixtures/tests_samples/conll/sample.json
--validation_file tests/fixtures/tests_samples/conll/sample.json
--output_dir {tmp_dir}
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=2
--num_train_epochs={epochs}
--seed 7
--checkpointing_steps epoch
--with_tracking
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 )
self.assertLess(result['''train_loss'''] , 0.5 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''ner_no_trainer''' ) ) )
@unittest.skip(reason='''Fix me @muellerzr''' )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: Tuple ) -> int:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py
--model_name_or_path bert-base-uncased
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--seed=42
--max_train_steps=10
--num_warmup_steps=2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--checkpointing_steps epoch
--with_tracking
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
# Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
self.assertGreaterEqual(result['''eval_f1'''] , 28 )
self.assertGreaterEqual(result['''eval_exact'''] , 28 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''qa_no_trainer''' ) ) )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: List[str] ) -> Tuple:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py
--model_name_or_path bert-base-uncased
--train_file tests/fixtures/tests_samples/swag/sample.json
--validation_file tests/fixtures/tests_samples/swag/sample.json
--output_dir {tmp_dir}
--max_train_steps=20
--num_warmup_steps=2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--with_tracking
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 )
self.assertTrue(os.path.exists(os.path.join(__A , '''swag_no_trainer''' ) ) )
@slow
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: List[Any] ) -> Optional[Any]:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py
--model_name_or_path t5-small
--train_file tests/fixtures/tests_samples/xsum/sample.json
--validation_file tests/fixtures/tests_samples/xsum/sample.json
--output_dir {tmp_dir}
--max_train_steps=50
--num_warmup_steps=8
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--checkpointing_steps epoch
--with_tracking
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertGreaterEqual(result['''eval_rouge1'''] , 10 )
self.assertGreaterEqual(result['''eval_rouge2'''] , 2 )
self.assertGreaterEqual(result['''eval_rougeL'''] , 7 )
self.assertGreaterEqual(result['''eval_rougeLsum'''] , 7 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''summarization_no_trainer''' ) ) )
@slow
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: Any ) -> Union[str, Any]:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/translation/run_translation_no_trainer.py
--model_name_or_path sshleifer/student_marian_en_ro_6_1
--source_lang en
--target_lang ro
--train_file tests/fixtures/tests_samples/wmt16/sample.json
--validation_file tests/fixtures/tests_samples/wmt16/sample.json
--output_dir {tmp_dir}
--max_train_steps=50
--num_warmup_steps=8
--num_beams=6
--learning_rate=3e-3
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--source_lang en_XX
--target_lang ro_RO
--checkpointing_steps epoch
--with_tracking
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertGreaterEqual(result['''eval_bleu'''] , 30 )
self.assertTrue(os.path.exists(os.path.join(__A , '''epoch_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''translation_no_trainer''' ) ) )
@slow
def __A ( self: Union[str, Any] ) -> Tuple:
_A = logging.StreamHandler(sys.stdout )
logger.addHandler(__A )
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py
--dataset_name huggingface/semantic-segmentation-test-sample
--output_dir {tmp_dir}
--max_train_steps=10
--num_warmup_steps=2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--checkpointing_steps epoch
""".split()
run_command(self._launch_args + testargs )
_A = get_results(__A )
self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 )
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def __A ( self: str ) -> Dict:
_A = self.get_auto_remove_tmp_dir()
_A = f"""
{self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py
--model_name_or_path google/vit-base-patch16-224-in21k
--dataset_name hf-internal-testing/cats_vs_dogs_sample
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--max_train_steps 2
--train_val_split 0.1
--seed 42
--output_dir {tmp_dir}
--with_tracking
--checkpointing_steps 1
""".split()
if is_cuda_and_apex_available():
testargs.append('''--fp16''' )
run_command(self._launch_args + testargs )
_A = get_results(__A )
# The base model scores a 25%
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 )
self.assertTrue(os.path.exists(os.path.join(__A , '''step_1''' ) ) )
self.assertTrue(os.path.exists(os.path.join(__A , '''image_classification_no_trainer''' ) ) )
| 719 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A ,_A = len(_lowercase ), len(grid[0] )
if (
min(_lowercase , _lowercase ) < 0
or row == row_length
or col == col_length
or (row, col) in visit
or grid[row][col] == 1
):
return 0
if row == row_length - 1 and col == col_length - 1:
return 1
visit.add((row, col) )
_A = 0
count += depth_first_search(_lowercase , row + 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , row - 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col + 1 , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col - 1 , _lowercase )
visit.remove((row, col) )
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DPMSolverMultistepScheduler,
TextToVideoSDPipeline,
UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
@skip_mps
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = TextToVideoSDPipeline
A_ = TEXT_TO_IMAGE_PARAMS
A_ = TEXT_TO_IMAGE_BATCH_PARAMS
# No `output_type`.
A_ = frozenset(
[
"num_inference_steps",
"generator",
"latents",
"return_dict",
"callback",
"callback_steps",
] )
def __A ( self: Optional[Any] ) -> List[Any]:
torch.manual_seed(0 )
_A = UNetaDConditionModel(
block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , )
_A = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=__A , set_alpha_to_one=__A , )
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=5_12 , )
_A = CLIPTextModel(__A )
_A = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
_A = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
}
return components
def __A ( self: Union[str, Any] , __A: List[Any] , __A: Tuple=0 ) -> int:
if str(__A ).startswith('''mps''' ):
_A = torch.manual_seed(__A )
else:
_A = torch.Generator(device=__A ).manual_seed(__A )
_A = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 6.0,
'''output_type''': '''pt''',
}
return inputs
def __A ( self: List[Any] ) -> Dict:
_A = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_A = self.get_dummy_components()
_A = TextToVideoSDPipeline(**__A )
_A = sd_pipe.to(__A )
sd_pipe.set_progress_bar_config(disable=__A )
_A = self.get_dummy_inputs(__A )
_A = '''np'''
_A = sd_pipe(**__A ).frames
_A = frames[0][-3:, -3:, -1]
assert frames[0].shape == (64, 64, 3)
_A = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __A ( self: Dict ) -> str:
self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__A , expected_max_diff=3e-3 )
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def __A ( self: Union[str, Any] ) -> List[Any]:
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__A , expected_max_diff=1e-2 )
@unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' )
def __A ( self: Any ) -> Optional[Any]:
pass
@unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' )
def __A ( self: Optional[Any] ) -> Optional[int]:
pass
@unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' )
def __A ( self: Optional[int] ) -> List[str]:
pass
def __A ( self: List[Any] ) -> Dict:
return super().test_progress_bar()
@slow
@skip_mps
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: List[Any] ) -> str:
_A = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy''' )
_A = TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''' )
_A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
_A = pipe.to('''cuda''' )
_A = '''Spiderman is surfing'''
_A = torch.Generator(device='''cpu''' ).manual_seed(0 )
_A = pipe(__A , generator=__A , num_inference_steps=25 , output_type='''pt''' ).frames
_A = video_frames.cpu().numpy()
assert np.abs(expected_video - video ).mean() < 5e-2
def __A ( self: List[Any] ) -> Union[str, Any]:
_A = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy''' )
_A = TextToVideoSDPipeline.from_pretrained('''damo-vilab/text-to-video-ms-1.7b''' )
_A = pipe.to('''cuda''' )
_A = '''Spiderman is surfing'''
_A = torch.Generator(device='''cpu''' ).manual_seed(0 )
_A = pipe(__A , generator=__A , num_inference_steps=2 , output_type='''pt''' ).frames
_A = video_frames.cpu().numpy()
assert np.abs(expected_video - video ).mean() < 5e-2
| 720 |
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
__A = NewType('DataClass', Any)
__A = NewType('DataClassType', Any)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , _lowercase ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError(
f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" )
def __A ( _lowercase ):
'''simple docstring'''
_A = {str(_lowercase ): choice for choice in choices}
return lambda _lowercase : str_to_choice.get(_lowercase , _lowercase )
def __A ( *,
_lowercase = None , _lowercase = None , _lowercase = dataclasses.MISSING , _lowercase = dataclasses.MISSING , _lowercase = None , **_lowercase , ):
'''simple docstring'''
if metadata is None:
# Important, don't use as default param in function signature because dict is mutable and shared across function calls
_A = {}
if aliases is not None:
_A = aliases
if help is not None:
_A = help
return dataclasses.field(metadata=_lowercase , default=_lowercase , default_factory=_lowercase , **_lowercase )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = 42
def __init__( self: Optional[Any] , __A: Union[DataClassType, Iterable[DataClassType]] , **__A: List[Any] ) -> str:
# To make the default appear when using --help
if "formatter_class" not in kwargs:
_A = ArgumentDefaultsHelpFormatter
super().__init__(**__A )
if dataclasses.is_dataclass(__A ):
_A = [dataclass_types]
_A = list(__A )
for dtype in self.dataclass_types:
self._add_dataclass_arguments(__A )
@staticmethod
def __A ( __A: ArgumentParser , __A: dataclasses.Field ) -> str:
_A = f"""--{field.name}"""
_A = field.metadata.copy()
# field.metadata is not used at all by Data Classes,
# it is provided as a third-party extension mechanism.
if isinstance(field.type , __A ):
raise RuntimeError(
'''Unresolved type detected, which should have been done with the help of '''
'''`typing.get_type_hints` method by default''' )
_A = kwargs.pop('''aliases''' , [] )
if isinstance(__A , __A ):
_A = [aliases]
_A = getattr(field.type , '''__origin__''' , field.type )
if origin_type is Union or (hasattr(__A , '''UnionType''' ) and isinstance(__A , types.UnionType )):
if str not in field.type.__args__ and (
len(field.type.__args__ ) != 2 or type(__A ) not in field.type.__args__
):
raise ValueError(
'''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
''' the argument parser only supports one type per argument.'''
f""" Problem encountered in field '{field.name}'.""" )
if type(__A ) not in field.type.__args__:
# filter `str` in Union
_A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
_A = getattr(field.type , '''__origin__''' , field.type )
elif bool not in field.type.__args__:
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
_A = (
field.type.__args__[0] if isinstance(__A , field.type.__args__[1] ) else field.type.__args__[1]
)
_A = getattr(field.type , '''__origin__''' , field.type )
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
_A = {}
if origin_type is Literal or (isinstance(field.type , __A ) and issubclass(field.type , __A )):
if origin_type is Literal:
_A = field.type.__args__
else:
_A = [x.value for x in field.type]
_A = make_choice_type_function(kwargs['''choices'''] )
if field.default is not dataclasses.MISSING:
_A = field.default
else:
_A = True
elif field.type is bool or field.type == Optional[bool]:
# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
_A = copy(__A )
# Hack because type=bool in argparse does not behave as we want.
_A = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
_A = False if field.default is dataclasses.MISSING else field.default
# This is the value that will get picked if we don't include --field_name in any way
_A = default
# This tells argparse we accept 0 or 1 value after --field_name
_A = '''?'''
# This is the value that will get picked if we do --field_name (without value)
_A = True
elif isclass(__A ) and issubclass(__A , __A ):
_A = field.type.__args__[0]
_A = '''+'''
if field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
elif field.default is dataclasses.MISSING:
_A = True
else:
_A = field.type
if field.default is not dataclasses.MISSING:
_A = field.default
elif field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
else:
_A = True
parser.add_argument(__A , *__A , **__A )
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need those changes/additional keys.
if field.default is True and (field.type is bool or field.type == Optional[bool]):
_A = False
parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__A )
def __A ( self: Dict , __A: DataClassType ) -> List[Any]:
if hasattr(__A , '''_argument_group_name''' ):
_A = self.add_argument_group(dtype._argument_group_name )
else:
_A = self
try:
_A = get_type_hints(__A )
except NameError:
raise RuntimeError(
f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
'''removing line of `from __future__ import annotations` which opts in Postponed '''
'''Evaluation of Annotations (PEP 563)''' )
except TypeError as ex:
# Remove this block when we drop Python 3.9 support
if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__A ):
_A = '''.'''.join(map(__A , sys.version_info[:3] ) )
raise RuntimeError(
f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
'''line of `from __future__ import annotations` which opts in union types as '''
'''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
'''support Python versions that lower than 3.10, you need to use '''
'''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
'''`X | None`.''' ) from ex
raise
for field in dataclasses.fields(__A ):
if not field.init:
continue
_A = type_hints[field.name]
self._parse_dataclass_field(__A , __A )
def __A ( self: int , __A: Any=None , __A: int=False , __A: Any=True , __A: Optional[Any]=None , __A: Any=None , ) -> Tuple[DataClass, ...]:
if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )):
_A = []
if args_filename:
args_files.append(Path(__A ) )
elif look_for_args_file and len(sys.argv ):
args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) )
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
_A = ArgumentParser()
args_file_parser.add_argument(__A , type=__A , action='''append''' )
# Use only remaining args for further parsing (remove the args_file_flag)
_A ,_A = args_file_parser.parse_known_args(args=__A )
_A = vars(__A ).get(args_file_flag.lstrip('''-''' ) , __A )
if cmd_args_file_paths:
args_files.extend([Path(__A ) for p in cmd_args_file_paths] )
_A = []
for args_file in args_files:
if args_file.exists():
file_args += args_file.read_text().split()
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
_A = file_args + args if args is not None else file_args + sys.argv[1:]
_A ,_A = self.parse_known_args(args=__A )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in vars(__A ).items() if k in keys}
for k in keys:
delattr(__A , __A )
_A = dtype(**__A )
outputs.append(__A )
if len(namespace.__dict__ ) > 0:
# additional namespace.
outputs.append(__A )
if return_remaining_strings:
return (*outputs, remaining_args)
else:
if remaining_args:
raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" )
return (*outputs,)
def __A ( self: Tuple , __A: Dict[str, Any] , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = set(args.keys() )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in args.items() if k in keys}
unused_keys.difference_update(inputs.keys() )
_A = dtype(**__A )
outputs.append(__A )
if not allow_extra_keys and unused_keys:
raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__A )}""" )
return tuple(__A )
def __A ( self: Tuple , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
with open(Path(__A ) , encoding='''utf-8''' ) as open_json_file:
_A = json.loads(open_json_file.read() )
_A = self.parse_dict(__A , allow_extra_keys=__A )
return tuple(__A )
def __A ( self: List[Any] , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = self.parse_dict(yaml.safe_load(Path(__A ).read_text() ) , allow_extra_keys=__A )
return tuple(__A )
| 62 | 0 |
import argparse
import json
import math
import os
import time
import traceback
import zipfile
from collections import Counter
import requests
def __A ( _lowercase , _lowercase=None ):
_A = None
if token is not None:
_A = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""}
_A = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"""
_A = requests.get(_lowercase , headers=_lowercase ).json()
_A = {}
try:
job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} )
_A = math.ceil((result['''total_count'''] - 1_00) / 1_00 )
for i in range(_lowercase ):
_A = requests.get(url + f"""&page={i + 2}""" , headers=_lowercase ).json()
job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} )
return job_links
except Exception:
print(f"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" )
return {}
def __A ( _lowercase , _lowercase=None ):
_A = None
if token is not None:
_A = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""}
_A = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100"""
_A = requests.get(_lowercase , headers=_lowercase ).json()
_A = {}
try:
artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} )
_A = math.ceil((result['''total_count'''] - 1_00) / 1_00 )
for i in range(_lowercase ):
_A = requests.get(url + f"""&page={i + 2}""" , headers=_lowercase ).json()
artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} )
return artifacts
except Exception:
print(f"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" )
return {}
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
_A = None
if token is not None:
_A = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""}
_A = requests.get(_lowercase , headers=_lowercase , allow_redirects=_lowercase )
_A = result.headers['''Location''']
_A = requests.get(_lowercase , allow_redirects=_lowercase )
_A = os.path.join(_lowercase , f"""{artifact_name}.zip""" )
with open(_lowercase , '''wb''' ) as fp:
fp.write(response.content )
def __A ( _lowercase , _lowercase=None ):
_A = []
_A = []
_A = None
with zipfile.ZipFile(_lowercase ) as z:
for filename in z.namelist():
if not os.path.isdir(_lowercase ):
# read the file
if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]:
with z.open(_lowercase ) as f:
for line in f:
_A = line.decode('''UTF-8''' ).strip()
if filename == "failures_line.txt":
try:
# `error_line` is the place where `error` occurs
_A = line[: line.index(''': ''' )]
_A = line[line.index(''': ''' ) + len(''': ''' ) :]
errors.append([error_line, error] )
except Exception:
# skip un-related lines
pass
elif filename == "summary_short.txt" and line.startswith('''FAILED ''' ):
# `test` is the test method that failed
_A = line[len('''FAILED ''' ) :]
failed_tests.append(_lowercase )
elif filename == "job_name.txt":
_A = line
if len(_lowercase ) != len(_lowercase ):
raise ValueError(
f"""`errors` and `failed_tests` should have the same number of elements. Got {len(_lowercase )} for `errors` """
f"""and {len(_lowercase )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some"""
''' problem.''' )
_A = None
if job_name and job_links:
_A = job_links.get(_lowercase , _lowercase )
# A list with elements of the form (line of error, error, failed test)
_A = [x + [y] + [job_link] for x, y in zip(_lowercase , _lowercase )]
return result
def __A ( _lowercase , _lowercase=None ):
_A = []
_A = [os.path.join(_lowercase , _lowercase ) for p in os.listdir(_lowercase ) if p.endswith('''.zip''' )]
for p in paths:
errors.extend(get_errors_from_single_artifact(_lowercase , job_links=_lowercase ) )
return errors
def __A ( _lowercase , _lowercase=None ):
_A = Counter()
counter.update([x[1] for x in logs] )
_A = counter.most_common()
_A = {}
for error, count in counts:
if error_filter is None or error not in error_filter:
_A = {'''count''': count, '''failed_tests''': [(x[2], x[0]) for x in logs if x[1] == error]}
_A = dict(sorted(r.items() , key=lambda _lowercase : item[1]["count"] , reverse=_lowercase ) )
return r
def __A ( _lowercase ):
_A = test.split('''::''' )[0]
if test.startswith('''tests/models/''' ):
_A = test.split('''/''' )[2]
else:
_A = None
return test
def __A ( _lowercase , _lowercase=None ):
_A = [(x[0], x[1], get_model(x[2] )) for x in logs]
_A = [x for x in logs if x[2] is not None]
_A = {x[2] for x in logs}
_A = {}
for test in tests:
_A = Counter()
# count by errors in `test`
counter.update([x[1] for x in logs if x[2] == test] )
_A = counter.most_common()
_A = {error: count for error, count in counts if (error_filter is None or error not in error_filter)}
_A = sum(error_counts.values() )
if n_errors > 0:
_A = {'''count''': n_errors, '''errors''': error_counts}
_A = dict(sorted(r.items() , key=lambda _lowercase : item[1]["count"] , reverse=_lowercase ) )
return r
def __A ( _lowercase ):
_A = '''| no. | error | status |'''
_A = '''|-:|:-|:-|'''
_A = [header, sep]
for error in reduced_by_error:
_A = reduced_by_error[error]['''count''']
_A = f"""| {count} | {error[:1_00]} | |"""
lines.append(_lowercase )
return "\n".join(_lowercase )
def __A ( _lowercase ):
_A = '''| model | no. of errors | major error | count |'''
_A = '''|-:|-:|-:|-:|'''
_A = [header, sep]
for model in reduced_by_model:
_A = reduced_by_model[model]['''count''']
_A ,_A = list(reduced_by_model[model]['''errors'''].items() )[0]
_A = f"""| {model} | {count} | {error[:60]} | {_count} |"""
lines.append(_lowercase )
return "\n".join(_lowercase )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.')
parser.add_argument(
'--output_dir',
type=str,
required=True,
help='Where to store the downloaded artifacts and other result files.',
)
parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.')
__A = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
__A = get_job_links(args.workflow_run_id, token=args.token)
__A = {}
# To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee.
# For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`.
if _job_links:
for k, v in _job_links.items():
# This is how GitHub actions combine job names.
if " / " in k:
__A = k.find(' / ')
__A = k[index + len(' / ') :]
__A = v
with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp:
json.dump(job_links, fp, ensure_ascii=False, indent=4)
__A = get_artifacts_links(args.workflow_run_id, token=args.token)
with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp:
json.dump(artifacts, fp, ensure_ascii=False, indent=4)
for idx, (name, url) in enumerate(artifacts.items()):
download_artifact(name, url, args.output_dir, args.token)
# Be gentle to GitHub
time.sleep(1)
__A = get_all_errors(args.output_dir, job_links=job_links)
# `e[1]` is the error
__A = Counter()
counter.update([e[1] for e in errors])
# print the top 30 most common test errors
__A = counter.most_common(30)
for item in most_common:
print(item)
with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp:
json.dump(errors, fp, ensure_ascii=False, indent=4)
__A = reduce_by_error(errors)
__A = reduce_by_model(errors)
__A = make_github_table(reduced_by_error)
__A = make_github_table_per_model(reduced_by_model)
with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp:
fp.write(sa)
with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp:
fp.write(sa)
| 721 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: Union[str, Any] , __A: int=2 , __A: List[str]=True , __A: List[Any]=False , __A: Union[str, Any]=10 , __A: Optional[int]=3 , __A: List[Any]=32 * 4 , __A: Dict=32 * 6 , __A: Optional[Any]=4 , __A: Any=32 , ) -> str:
_A = parent
_A = batch_size
_A = is_training
_A = use_auxiliary_loss
_A = num_queries
_A = num_channels
_A = min_size
_A = max_size
_A = num_labels
_A = mask_feature_size
def __A ( self: Dict ) -> Optional[int]:
_A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
__A )
_A = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A )
_A = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5
).float()
_A = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long()
_A = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __A ( self: Optional[Any] ) -> Tuple:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __A ( self: Dict ) -> Tuple:
_A ,_A ,_A ,_A ,_A = self.prepare_config_and_inputs()
_A = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: Dict ) -> int:
_A = output.encoder_hidden_states
_A = output.pixel_decoder_hidden_states
_A = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , config.decoder_config.decoder_layers )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Any , __A: Dict=False ) -> Any:
with torch.no_grad():
_A = MaskFormerModel(config=__A )
model.to(__A )
model.eval()
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A , output_hidden_states=__A )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(__A , __A )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Union[str, Any] , __A: Union[str, Any] , __A: List[Any] ) -> int:
_A = MaskFormerForInstanceSegmentation(config=__A )
model.to(__A )
model.eval()
def comm_check_on_output(__A: int ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A )
comm_check_on_output(__A )
_A = model(
pixel_values=__A , pixel_mask=__A , mask_labels=__A , class_labels=__A )
comm_check_on_output(__A )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
A_ = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
A_ = False
A_ = False
A_ = False
A_ = False
def __A ( self: int ) -> Tuple:
_A = MaskFormerModelTester(self )
_A = ConfigTester(self , config_class=__A , has_text_modality=__A )
def __A ( self: List[Any] ) -> Dict:
self.config_tester.run_common_tests()
def __A ( self: Optional[Any] ) -> int:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Dict ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__A )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def __A ( self: int ) -> Tuple:
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def __A ( self: List[Any] ) -> Any:
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def __A ( self: Union[str, Any] ) -> Optional[int]:
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def __A ( self: int ) -> List[str]:
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def __A ( self: Union[str, Any] ) -> List[Any]:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: List[Any] ) -> Any:
pass
def __A ( self: Dict ) -> Optional[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A )
_A = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_A = [*signature.parameters.keys()]
_A = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __A )
@slow
def __A ( self: int ) -> Optional[Any]:
for model_name in ["facebook/maskformer-swin-small-coco"]:
_A = MaskFormerModel.from_pretrained(__A )
self.assertIsNotNone(__A )
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = (self.model_tester.min_size,) * 2
_A = {
'''pixel_values''': torch.randn((2, 3, *size) , device=__A ),
'''mask_labels''': torch.randn((2, 10, *size) , device=__A ),
'''class_labels''': torch.zeros(2 , 10 , device=__A ).long(),
}
_A = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__A )
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
def __A ( self: Optional[Any] ) -> List[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Any ) -> Tuple:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A ).to(__A )
_A = model(**__A , output_attentions=__A )
self.assertTrue(outputs.attentions is not None )
def __A ( self: Dict ) -> Union[str, Any]:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A ).loss
loss.backward()
def __A ( self: Tuple ) -> Optional[Any]:
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = True
_A = True
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A )
_A = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
_A = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
_A = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
_A = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=__A )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__A = 1e-4
def __A ( ):
'''simple docstring'''
_A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self: Union[str, Any] ) -> Optional[int]:
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def __A ( self: List[Any] ) -> Any:
_A = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(__A )
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
_A = torch.tensor(
[[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Dict ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [
[-1.3_737_124, -1.7_724_937, -1.9_364_233],
[-1.5_977_281, -1.9_867_939, -2.1_523_695],
[-1.5_795_398, -1.9_269_832, -2.093_942],
]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: List[Any] ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Optional[Any] ) -> str:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors='''pt''' , )
_A = inputs['''pixel_values'''].to(__A )
_A = [el.to(__A ) for el in inputs['''mask_labels''']]
_A = [el.to(__A ) for el in inputs['''class_labels''']]
with torch.no_grad():
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
| 62 | 0 |
from __future__ import annotations
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ): # noqa: E741
'''simple docstring'''
while r - l > 1:
_A = (l + r) // 2
if v[m] >= key:
_A = m
else:
_A = m # noqa: E741
return r
def __A ( _lowercase ):
'''simple docstring'''
if len(_lowercase ) == 0:
return 0
_A = [0] * len(_lowercase )
_A = 1
_A = v[0]
for i in range(1 , len(_lowercase ) ):
if v[i] < tail[0]:
_A = v[i]
elif v[i] > tail[length - 1]:
_A = v[i]
length += 1
else:
_A = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 700 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Optional[int] , __A: Optional[Any] ) -> str:
_A = question_encoder
_A = generator
_A = self.question_encoder
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Dict:
if os.path.isfile(__A ):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(__A , exist_ok=__A )
_A = os.path.join(__A , '''question_encoder_tokenizer''' )
_A = os.path.join(__A , '''generator_tokenizer''' )
self.question_encoder.save_pretrained(__A )
self.generator.save_pretrained(__A )
@classmethod
def __A ( cls: Optional[Any] , __A: List[str] , **__A: int ) -> Any:
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
_A = kwargs.pop('''config''' , __A )
if config is None:
_A = RagConfig.from_pretrained(__A )
_A = AutoTokenizer.from_pretrained(
__A , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' )
_A = AutoTokenizer.from_pretrained(
__A , config=config.generator , subfolder='''generator_tokenizer''' )
return cls(question_encoder=__A , generator=__A )
def __call__( self: int , *__A: Optional[int] , **__A: List[str] ) -> int:
return self.current_tokenizer(*__A , **__A )
def __A ( self: Dict , *__A: List[str] , **__A: List[str] ) -> Dict:
return self.generator.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Tuple , **__A: List[str] ) -> Tuple:
return self.generator.decode(*__A , **__A )
def __A ( self: Dict ) -> List[str]:
_A = self.question_encoder
def __A ( self: Union[str, Any] ) -> int:
_A = self.generator
def __A ( self: Dict , __A: List[str] , __A: Optional[List[str]] = None , __A: Optional[int] = None , __A: Optional[int] = None , __A: str = "longest" , __A: str = None , __A: bool = True , **__A: Tuple , ) -> BatchEncoding:
warnings.warn(
'''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
'''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
'''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
'''details''' , __A , )
if max_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
__A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , )
_A = labels['''input_ids''']
return model_inputs
| 62 | 0 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(_lowercase , '''utf-8''' )
with zstd.open(_lowercase , '''wb''' ) as f:
f.write(_lowercase )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , _lowercase ) , '''w''' ) as f:
f.write(_lowercase )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=_lowercase , extract_compressed_file=_lowercase )
_A = cached_path(_lowercase , download_config=_lowercase )
with open(_lowercase ) as f:
_A = f.read()
with open(_lowercase ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , _lowercase )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(_lowercase ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=_lowercase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowercase )
)
_A = cached_path(_lowercase , download_config=_lowercase )
assert Path(_lowercase ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(_lowercase ).resolve() )
assert cached_path(_lowercase ) == text_file
# relative path
_A = str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowercase ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(_lowercase ):
cached_path(_lowercase )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(_lowercase ):
cached_path(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(_lowercase ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( ):
'''simple docstring'''
with pytest.raises(_lowercase ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
http_get('''https://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
ftp_get('''ftp://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
fsspec_get('''s3://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
fsspec_head('''s3://huggingface.co''' )
| 701 |
from __future__ import annotations
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ): # noqa: E741
'''simple docstring'''
while r - l > 1:
_A = (l + r) // 2
if v[m] >= key:
_A = m
else:
_A = m # noqa: E741
return r
def __A ( _lowercase ):
'''simple docstring'''
if len(_lowercase ) == 0:
return 0
_A = [0] * len(_lowercase )
_A = 1
_A = v[0]
for i in range(1 , len(_lowercase ) ):
if v[i] < tail[0]:
_A = v[i]
elif v[i] > tail[length - 1]:
_A = v[i]
length += 1
else:
_A = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
import argparse
import os
import sys
from unittest.mock import patch
import pytorch_lightning as pl
import timeout_decorator
import torch
from distillation import SummarizationDistiller, distill_main
from finetune import SummarizationModule, main
from transformers import MarianMTModel
from transformers.file_utils import cached_path
from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow
from utils import load_json
__A = 'sshleifer/mar_enro_6_3_student'
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __A ( self: Tuple ) -> Dict:
super().setUp()
_A = cached_path(
'''https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz''' , extract_compressed_file=__A , )
_A = f"""{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k"""
@slow
@require_torch_gpu
def __A ( self: Any ) -> List[Any]:
MarianMTModel.from_pretrained(__A )
@slow
@require_torch_gpu
def __A ( self: Tuple ) -> Optional[Any]:
_A = {
'''$MAX_LEN''': 64,
'''$BS''': 64,
'''$GAS''': 1,
'''$ENRO_DIR''': self.data_dir,
'''facebook/mbart-large-cc25''': MARIAN_MODEL,
# "val_check_interval=0.25": "val_check_interval=1.0",
'''--learning_rate=3e-5''': '''--learning_rate 3e-4''',
'''--num_train_epochs 6''': '''--num_train_epochs 1''',
}
# Clean up bash script
_A = (self.test_file_dir / '''train_mbart_cc25_enro.sh''').open().read().split('''finetune.py''' )[1].strip()
_A = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' )
for k, v in env_vars_to_replace.items():
_A = bash_script.replace(__A , str(__A ) )
_A = self.get_auto_remove_tmp_dir()
# bash_script = bash_script.replace("--fp16 ", "")
_A = f"""
--output_dir {output_dir}
--tokenizer_name Helsinki-NLP/opus-mt-en-ro
--sortish_sampler
--do_predict
--gpus 1
--freeze_encoder
--n_train 40000
--n_val 500
--n_test 500
--fp16_opt_level O1
--num_sanity_val_steps 0
--eval_beams 2
""".split()
# XXX: args.gpus > 1 : handle multi_gpu in the future
_A = ['''finetune.py'''] + bash_script.split() + args
with patch.object(__A , '''argv''' , __A ):
_A = argparse.ArgumentParser()
_A = pl.Trainer.add_argparse_args(__A )
_A = SummarizationModule.add_model_specific_args(__A , os.getcwd() )
_A = parser.parse_args()
_A = main(__A )
# Check metrics
_A = load_json(model.metrics_save_path )
_A = metrics['''val'''][0]
_A = metrics['''val'''][-1]
self.assertEqual(len(metrics['''val'''] ) , (args.max_epochs / args.val_check_interval) )
assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , __A )
self.assertGreater(last_step_stats['''val_avg_gen_time'''] , 0.01 )
# model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?)
self.assertLessEqual(last_step_stats['''val_avg_gen_time'''] , 1.0 )
# test learning requirements:
# 1. BLEU improves over the course of training by more than 2 pts
self.assertGreater(last_step_stats['''val_avg_bleu'''] - first_step_stats['''val_avg_bleu'''] , 2 )
# 2. BLEU finishes above 17
self.assertGreater(last_step_stats['''val_avg_bleu'''] , 17 )
# 3. test BLEU and val BLEU within ~1.1 pt.
self.assertLess(abs(metrics['''val'''][-1]['''val_avg_bleu'''] - metrics['''test'''][-1]['''test_avg_bleu'''] ) , 1.1 )
# check lightning ckpt can be loaded and has a reasonable statedict
_A = os.listdir(__A )
_A = [x for x in contents if x.endswith('''.ckpt''' )][0]
_A = os.path.join(args.output_dir , __A )
_A = torch.load(__A , map_location='''cpu''' )
_A = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight'''
assert expected_key in ckpt["state_dict"]
assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa
# TODO: turn on args.do_predict when PL bug fixed.
if args.do_predict:
_A = {os.path.basename(__A ) for p in contents}
assert "test_generations.txt" in contents
assert "test_results.txt" in contents
# assert len(metrics["val"]) == desired_n_evals
assert len(metrics['''test'''] ) == 1
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@timeout_decorator.timeout(6_00 )
@slow
@require_torch_gpu
def __A ( self: List[str] ) -> Union[str, Any]:
_A = f"""{self.test_file_dir_str}/test_data/wmt_en_ro"""
_A = {
'''--fp16_opt_level=O1''': '''''',
'''$MAX_LEN''': 1_28,
'''$BS''': 16,
'''$GAS''': 1,
'''$ENRO_DIR''': data_dir,
'''$m''': '''sshleifer/student_marian_en_ro_6_1''',
'''val_check_interval=0.25''': '''val_check_interval=1.0''',
}
# Clean up bash script
_A = (
(self.test_file_dir / '''distil_marian_no_teacher.sh''').open().read().split('''distillation.py''' )[1].strip()
)
_A = bash_script.replace('''\\\n''' , '''''' ).strip().replace('''"$@"''' , '''''' )
_A = bash_script.replace('''--fp16 ''' , ''' ''' )
for k, v in env_vars_to_replace.items():
_A = bash_script.replace(__A , str(__A ) )
_A = self.get_auto_remove_tmp_dir()
_A = bash_script.replace('''--fp16''' , '''''' )
_A = 6
_A = (
['''distillation.py''']
+ bash_script.split()
+ [
f"""--output_dir={output_dir}""",
'''--gpus=1''',
'''--learning_rate=1e-3''',
f"""--num_train_epochs={epochs}""",
'''--warmup_steps=10''',
'''--val_check_interval=1.0''',
'''--do_predict''',
]
)
with patch.object(__A , '''argv''' , __A ):
_A = argparse.ArgumentParser()
_A = pl.Trainer.add_argparse_args(__A )
_A = SummarizationDistiller.add_model_specific_args(__A , os.getcwd() )
_A = parser.parse_args()
# assert args.gpus == gpus THIS BREAKS for multi_gpu
_A = distill_main(__A )
# Check metrics
_A = load_json(model.metrics_save_path )
_A = metrics['''val'''][0]
_A = metrics['''val'''][-1]
assert len(metrics['''val'''] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check
assert last_step_stats["val_avg_gen_time"] >= 0.01
assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing
assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved.
assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , __A )
# check lightning ckpt can be loaded and has a reasonable statedict
_A = os.listdir(__A )
_A = [x for x in contents if x.endswith('''.ckpt''' )][0]
_A = os.path.join(args.output_dir , __A )
_A = torch.load(__A , map_location='''cpu''' )
_A = '''model.model.decoder.layers.0.encoder_attn_layer_norm.weight'''
assert expected_key in ckpt["state_dict"]
assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa
# TODO: turn on args.do_predict when PL bug fixed.
if args.do_predict:
_A = {os.path.basename(__A ) for p in contents}
assert "test_generations.txt" in contents
assert "test_results.txt" in contents
# assert len(metrics["val"]) == desired_n_evals
assert len(metrics['''test'''] ) == 1
| 702 |
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
__A = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "sequence-classification"
def __init__( self: str , __A: Union[str, Any] ) -> List[str]:
if type(__A ) == dict:
_A = Namespace(**__A )
_A = glue_output_modes[hparams.task]
_A = glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def __A ( self: Optional[Any] , **__A: Union[str, Any] ) -> Optional[int]:
return self.model(**__A )
def __A ( self: Any , __A: Union[str, Any] , __A: int ) -> Optional[Any]:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A = outputs[0]
_A = self.trainer.lr_schedulers[0]['''scheduler''']
_A = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def __A ( self: List[str] ) -> Dict:
_A = self.hparams
_A = processors[args.task]()
_A = processor.get_labels()
for mode in ["train", "dev"]:
_A = self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('''Loading features from cached file %s''' , __A )
else:
logger.info('''Creating features from dataset file at %s''' , args.data_dir )
_A = (
processor.get_dev_examples(args.data_dir )
if mode == '''dev'''
else processor.get_train_examples(args.data_dir )
)
_A = convert_examples_to_features(
__A , 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''' , __A )
torch.save(__A , __A )
def __A ( self: List[str] , __A: str , __A: int , __A: bool = False ) -> DataLoader:
_A = '''dev''' if mode == '''test''' else mode
_A = self._feature_file(__A )
logger.info('''Loading features from cached file %s''' , __A )
_A = torch.load(__A )
_A = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_A = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_A = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_A = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_A = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def __A ( self: List[str] , __A: str , __A: Tuple ) -> str:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A ,_A = outputs[:2]
_A = logits.detach().cpu().numpy()
_A = inputs['''labels'''].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __A ( self: str , __A: Dict ) -> tuple:
_A = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item()
_A = np.concatenate([x['''pred'''] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_A = np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_A = np.squeeze(__A )
_A = np.concatenate([x['''target'''] for x in outputs] , axis=0 )
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_A = dict(results.items() )
_A = results
return ret, preds_list, out_label_list
def __A ( self: Any , __A: list ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = ret['''log''']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __A ( self: int , __A: Union[str, Any] ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = 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 ( __A: Optional[Any] , __A: Optional[Any] ) -> Optional[Any]:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'''--max_seq_length''' , default=1_28 , type=__A , 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=__A , required=__A , help='''The GLUE task to run''' , )
parser.add_argument(
'''--gpus''' , default=0 , type=__A , 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 __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser()
add_generic_args(_lowercase , os.getcwd() )
_A = GLUETransformer.add_model_specific_args(_lowercase , os.getcwd() )
_A = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_A = os.path.join(
'''./results''' , f"""{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}""" , )
os.makedirs(args.output_dir )
_A = GLUETransformer(_lowercase )
_A = generic_train(_lowercase , _lowercase )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_A = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=_lowercase ) )
_A = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(_lowercase )
if __name__ == "__main__":
main()
| 62 | 0 |
import sys
import turtle
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , ):
'''simple docstring'''
my_pen.up()
my_pen.goto(vertexa[0] , vertexa[1] )
my_pen.down()
my_pen.goto(vertexa[0] , vertexa[1] )
my_pen.goto(vertexa[0] , vertexa[1] )
my_pen.goto(vertexa[0] , vertexa[1] )
if depth == 0:
return
triangle(_lowercase , get_mid(_lowercase , _lowercase ) , get_mid(_lowercase , _lowercase ) , depth - 1 )
triangle(_lowercase , get_mid(_lowercase , _lowercase ) , get_mid(_lowercase , _lowercase ) , depth - 1 )
triangle(_lowercase , get_mid(_lowercase , _lowercase ) , get_mid(_lowercase , _lowercase ) , depth - 1 )
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError(
'Correct format for using this script: '
'python fractals.py <int:depth_for_fractal>'
)
__A = turtle.Turtle()
my_pen.ht()
my_pen.speed(5)
my_pen.pencolor('red')
__A = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle
triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
| 703 |
from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def __A ( _lowercase = "" ):
'''simple docstring'''
_A = url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250'''
_A = BeautifulSoup(requests.get(_lowercase ).text , '''html.parser''' )
_A = soup.find_all('''td''' , attrs='''titleColumn''' )
_A = soup.find_all('''td''' , class_='''ratingColumn imdbRating''' )
return {
title.a.text: float(rating.strong.text )
for title, rating in zip(_lowercase , _lowercase )
}
def __A ( _lowercase = "IMDb_Top_250_Movies.csv" ):
'''simple docstring'''
_A = get_imdb_top_aaa_movies()
with open(_lowercase , '''w''' , newline='''''' ) as out_file:
_A = csv.writer(_lowercase )
writer.writerow(['''Movie title''', '''IMDb rating'''] )
for title, rating in movies.items():
writer.writerow([title, rating] )
if __name__ == "__main__":
write_movies()
| 62 | 0 |
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
__A = trt.Logger(trt.Logger.WARNING)
__A = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
__A = logging.getLogger(__name__)
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--onnx_model_path',
default=None,
type=str,
required=True,
help='Path to ONNX model: ',
)
parser.add_argument(
'--output_dir',
default=None,
type=str,
required=True,
help='The output directory where the model checkpoints and predictions will be written.',
)
# Other parameters
parser.add_argument(
'--tokenizer_name',
default='',
type=str,
required=True,
help='Pretrained tokenizer name or path if not the same as model_name',
)
parser.add_argument(
'--version_2_with_negative',
action='store_true',
help='If true, the SQuAD examples contain some that do not have an answer.',
)
parser.add_argument(
'--null_score_diff_threshold',
type=float,
default=0.0,
help='If null_score - best_non_null is greater than the threshold predict null.',
)
parser.add_argument(
'--max_seq_length',
default=384,
type=int,
help=(
'The maximum total input sequence length after WordPiece tokenization. Sequences '
'longer than this will be truncated, and sequences shorter than this will be padded.'
),
)
parser.add_argument(
'--doc_stride',
default=128,
type=int,
help='When splitting up a long document into chunks, how much stride to take between chunks.',
)
parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.')
parser.add_argument(
'--n_best_size',
default=20,
type=int,
help='The total number of n-best predictions to generate in the nbest_predictions.json output file.',
)
parser.add_argument(
'--max_answer_length',
default=30,
type=int,
help=(
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
),
)
parser.add_argument('--seed', type=int, default=42, help='random seed for initialization')
parser.add_argument(
'--dataset_name',
type=str,
default=None,
required=True,
help='The name of the dataset to use (via the datasets library).',
)
parser.add_argument(
'--dataset_config_name',
type=str,
default=None,
help='The configuration name of the dataset to use (via the datasets library).',
)
parser.add_argument(
'--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.'
)
parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets')
parser.add_argument(
'--fp16',
action='store_true',
help='Whether to use 16-bit (mixed) precision instead of 32-bit',
)
parser.add_argument(
'--int8',
action='store_true',
help='Whether to use INT8',
)
__A = parser.parse_args()
if args.tokenizer_name:
__A = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'You are instantiating a new tokenizer from scratch. This is not supported by this script.'
'You can do it from another script, save it, and load it from here, using --tokenizer_name.'
)
logger.info('Training/evaluation parameters %s', args)
__A = args.per_device_eval_batch_size
__A = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
__A = True
__A = 'temp_engine/bert-fp32.engine'
if args.fpaa:
__A = 'temp_engine/bert-fp16.engine'
if args.inta:
__A = 'temp_engine/bert-int8.engine'
# import ONNX file
if not os.path.exists('temp_engine'):
os.makedirs('temp_engine')
__A = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, 'rb') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
__A = [network.get_input(i) for i in range(network.num_inputs)]
__A = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
__A = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
__A = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
__A = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, 'wb') as f:
f.write(engine.serialize())
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
_A = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
_A = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , _lowercase )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , _lowercase )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , _lowercase )
# start time
_A = time.time()
# Run inference
context.execute_async(
bindings=[int(_lowercase ) for d_inp in d_inputs] + [int(_lowercase ), int(_lowercase )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(_lowercase , _lowercase , _lowercase )
cuda.memcpy_dtoh_async(_lowercase , _lowercase , _lowercase )
# Synchronize the stream and take time
stream.synchronize()
# end time
_A = time.time()
_A = end_time - start_time
_A = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
__A = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
__A = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('Evaluation requires a dataset name')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
__A = raw_datasets['validation'].column_names
__A = 'question' if 'question' in column_names else column_names[0]
__A = 'context' if 'context' in column_names else column_names[1]
__A = 'answers' if 'answers' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
__A = tokenizer.padding_side == 'right'
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
__A = min(args.max_seq_length, tokenizer.model_max_length)
def __A ( _lowercase ):
'''simple docstring'''
_A = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
_A = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=_lowercase , stride=args.doc_stride , return_overflowing_tokens=_lowercase , return_offsets_mapping=_lowercase , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
_A = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
_A = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
_A = tokenized_examples.sequence_ids(_lowercase )
_A = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
_A = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
_A = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
__A = raw_datasets['validation']
# Validation Feature Creation
__A = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='Running tokenizer on validation dataset',
)
__A = default_data_collator
__A = eval_dataset.remove_columns(['example_id', 'offset_mapping'])
__A = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def __A ( _lowercase , _lowercase , _lowercase , _lowercase="eval" ):
'''simple docstring'''
_A = postprocess_qa_predictions(
examples=_lowercase , features=_lowercase , predictions=_lowercase , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=_lowercase , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
_A = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
_A = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
_A = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=_lowercase , label_ids=_lowercase )
__A = load_metric('squad_v2' if args.version_2_with_negative else 'squad')
# Evaluation!
logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path)
with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def __A ( _lowercase ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(_lowercase ) ) * engine.get_binding_dtype(_lowercase ).itemsize
# Allocate device memory for inputs and outputs.
__A = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
__A = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
__A = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
__A = cuda.mem_alloc(h_outputa.nbytes)
__A = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
__A = cuda.Stream()
# Evaluation
logger.info('***** Running Evaluation *****')
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
__A = 0.0
__A = 0
__A = timeit.default_timer()
__A = None
for step, batch in enumerate(eval_dataloader):
__A , __A = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
__A , __A = outputs
__A = torch.tensor(start_logits)
__A = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
__A = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100)
__A = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100)
__A = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
__A = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if all_preds is not None:
__A = nested_truncate(all_preds, len(eval_dataset))
__A = timeit.default_timer() - start_time
logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 1000 / niter))
logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 1000))
logger.info('Total Number of Inference = %d', niter)
__A = post_processing_function(eval_examples, eval_dataset, all_preds)
__A = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 704 |
import json
import os
import unittest
from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
VOCAB_FILES_NAMES,
BlenderbotSmallTokenizer,
)
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = BlenderbotSmallTokenizer
A_ = False
def __A ( self: List[str] ) -> int:
super().setUp()
_A = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__''']
_A = dict(zip(__A , range(len(__A ) ) ) )
_A = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', '''''']
_A = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''}
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_A = 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 __A ( self: str , **__A: Optional[Any] ) -> Dict:
kwargs.update(self.special_tokens_map )
return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__A )
def __A ( self: str , __A: List[str] ) -> int:
_A = '''adapt act apte'''
_A = '''adapt act apte'''
return input_text, output_text
def __A ( self: Union[str, Any] ) -> Any:
_A = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_A = '''adapt act apte'''
_A = ['''adapt''', '''act''', '''ap@@''', '''te''']
_A = tokenizer.tokenize(__A )
self.assertListEqual(__A , __A )
_A = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
_A = [0, 1, 2, 3, 4, 5]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
def __A ( self: Any ) -> List[str]:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
assert tok('''sam''' ).input_ids == [13_84]
_A = '''I am a small frog.'''
_A = tok([src_text] , padding=__A , truncation=__A )['''input_ids''']
_A = tok.batch_decode(__A , skip_special_tokens=__A , clean_up_tokenization_spaces=__A )[0]
assert src_text != decoded # I wish it did!
assert decoded == "i am a small frog ."
def __A ( self: Any ) -> int:
_A = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
_A = '''I am a small frog .'''
_A = '''.'''
_A = tok(__A )['''input_ids''']
_A = tok(__A )['''input_ids''']
assert encoded[-1] == encoded_dot[0]
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__A = {
'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MegaForCausalLM',
'MegaForMaskedLM',
'MegaForMultipleChoice',
'MegaForQuestionAnswering',
'MegaForSequenceClassification',
'MegaForTokenClassification',
'MegaModel',
'MegaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 705 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json',
'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "roberta"
def __init__( self: Dict , __A: int=5_02_65 , __A: Union[str, Any]=7_68 , __A: Union[str, Any]=12 , __A: str=12 , __A: int=30_72 , __A: str="gelu" , __A: Union[str, Any]=0.1 , __A: int=0.1 , __A: Optional[int]=5_12 , __A: Union[str, Any]=2 , __A: str=0.02 , __A: str=1e-12 , __A: Any=1 , __A: str=0 , __A: Any=2 , __A: Optional[int]="absolute" , __A: Optional[Any]=True , __A: Union[str, Any]=None , **__A: List[str] , ) -> Dict:
super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A )
_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 SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
@property
def __A ( self: Dict ) -> Mapping[str, Mapping[int, str]]:
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),
] )
| 62 | 0 |
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import LevitImageProcessor
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __init__( self: Optional[Any] , __A: Optional[Any] , __A: Optional[int]=7 , __A: List[Any]=3 , __A: Tuple=18 , __A: Dict=30 , __A: List[Any]=4_00 , __A: int=True , __A: str=None , __A: List[str]=True , __A: Dict=None , __A: Optional[int]=True , __A: Optional[int]=[0.5, 0.5, 0.5] , __A: str=[0.5, 0.5, 0.5] , ) -> Dict:
_A = size if size is not None else {'''shortest_edge''': 18}
_A = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
_A = parent
_A = batch_size
_A = num_channels
_A = image_size
_A = min_resolution
_A = max_resolution
_A = do_resize
_A = size
_A = do_center_crop
_A = crop_size
_A = do_normalize
_A = image_mean
_A = image_std
def __A ( self: int ) -> List[str]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"do_center_crop": self.do_center_crop,
"size": self.size,
"crop_size": self.crop_size,
}
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = LevitImageProcessor if is_vision_available() else None
def __A ( self: Dict ) -> Union[str, Any]:
_A = LevitImageProcessingTester(self )
@property
def __A ( self: Optional[int] ) -> Dict:
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self: Union[str, Any] ) -> Dict:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , '''image_mean''' ) )
self.assertTrue(hasattr(__A , '''image_std''' ) )
self.assertTrue(hasattr(__A , '''do_normalize''' ) )
self.assertTrue(hasattr(__A , '''do_resize''' ) )
self.assertTrue(hasattr(__A , '''do_center_crop''' ) )
self.assertTrue(hasattr(__A , '''size''' ) )
def __A ( self: int ) -> Tuple:
_A = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 18} )
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} )
_A = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 )
self.assertEqual(image_processor.size , {'''shortest_edge''': 42} )
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} )
def __A ( self: List[Any] ) -> Any:
pass
def __A ( self: Optional[int] ) -> Optional[Any]:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_A = image_processing(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def __A ( self: List[str] ) -> Tuple:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A )
for image in image_inputs:
self.assertIsInstance(__A , np.ndarray )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_A = image_processing(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def __A ( self: List[str] ) -> str:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A )
for image in image_inputs:
self.assertIsInstance(__A , torch.Tensor )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_A = image_processing(__A , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
| 706 |
import logging
import os
import quant_trainer
import torch
from torch.utils.data import DataLoader
from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput
__A = logging.getLogger(__name__)
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __init__( self: int , *__A: str , __A: List[Any]=None , __A: Union[str, Any]=None , __A: List[Any]=None , **__A: int ) -> List[Any]:
super().__init__(*__A , **__A )
_A = eval_examples
_A = post_process_function
_A = quant_trainer_args
_A = 1_28 # default number of calibration samples
def __A ( self: Union[str, Any] , __A: List[Any]=None ) -> Optional[Any]:
if calib_dataset is None and self.calib_dataset is None:
raise ValueError('''Trainer: calibration requires an calib_dataset.''' )
_A = calib_dataset if calib_dataset is not None else self.calib_dataset
_A = self._remove_unused_columns(__A , description='''Calibration''' )
return DataLoader(
__A , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__A , )
def __A ( self: List[Any] , __A: Any=None ) -> Optional[int]:
_A = self.train_dataset if calib_dataset is None else calib_dataset
_A = self.get_calib_dataloader(__A )
_A = self.model
quant_trainer.configure_model(__A , self.quant_trainer_args , calib=__A )
model.eval()
quant_trainer.enable_calibration(__A )
logger.info('''***** Running calibration *****''' )
logger.info(f""" Num examples = {self.calib_num}""" )
logger.info(f""" Batch size = {calib_dataloader.batch_size}""" )
for step, inputs in enumerate(__A ):
# Prediction step
_A ,_A ,_A = self.prediction_step(__A , __A , prediction_loss_only=__A )
if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
break
quant_trainer.finish_calibration(__A , self.quant_trainer_args )
_A = model
def __A ( self: Any , __A: Dict=None , __A: Tuple=None , __A: List[Any]=None , __A: str = "eval" ) -> int:
_A = self.eval_dataset if eval_dataset is None else eval_dataset
_A = self.get_eval_dataloader(__A )
_A = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is not None and self.compute_metrics is not None:
_A = self.post_process_function(__A , __A , output.predictions )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
self.log(__A )
else:
_A = {}
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
_A = self.callback_handler.on_evaluate(self.args , self.state , self.control , __A )
return metrics
def __A ( self: Union[str, Any] , __A: Optional[int] , __A: int , __A: List[Any]=None , __A: str = "test" ) -> Union[str, Any]:
_A = self.get_test_dataloader(__A )
# Temporarily disable metric computation, we will do it in the loop here.
_A = self.compute_metrics
_A = None
_A = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
_A = eval_loop(
__A , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__A , )
finally:
_A = compute_metrics
if self.post_process_function is None or self.compute_metrics is None:
return output
_A = self.post_process_function(__A , __A , output.predictions , '''predict''' )
_A = self.compute_metrics(__A )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
_A = metrics.pop(__A )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__A )
def __A ( self: Tuple , __A: Optional[Any]="./" ) -> List[str]:
_A = self.eval_dataset
_A = self.get_eval_dataloader(__A )
_A = next(iter(__A ) )
# saving device - to make it consistent
_A = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' )
# convert to tuple
_A = tuple(v.to(__A ) for k, v in batch.items() )
logger.info('''Converting model to be onnx compatible''' )
from pytorch_quantization.nn import TensorQuantizer
_A = True
_A = self.model.to(__A )
model.eval()
model.float()
_A = model.module if hasattr(__A , '''module''' ) else model
quant_trainer.configure_model(__A , self.quant_trainer_args )
_A = os.path.join(__A , '''model.onnx''' )
logger.info(f"""exporting model to {output_model_file}""" )
_A = {0: '''batch_size''', 1: '''seq_len'''}
torch.onnx.export(
__A , __A , __A , export_params=__A , opset_version=13 , do_constant_folding=__A , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={
'''input_ids''': axes,
'''attention_mask''': axes,
'''token_type_ids''': axes,
'''output_start_logits''': axes,
'''output_end_logits''': axes,
} , verbose=__A , )
logger.info('''onnx export finished''' )
| 62 | 0 |
import unittest
import torch
from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel
from diffusers.training_utils import set_seed
from diffusers.utils.testing_utils import slow
__A = False
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: str , __A: Optional[Any]=32 ) -> int:
set_seed(0 )
_A = UNetaDModel(sample_size=__A , in_channels=3 , out_channels=3 )
_A = torch.optim.SGD(model.parameters() , lr=0.0_001 )
return model, optimizer
@slow
def __A ( self: Union[str, Any] ) -> Tuple:
_A = '''cpu''' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable
_A = DDPMScheduler(
num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=__A , )
_A = DDIMScheduler(
num_train_timesteps=10_00 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule='''linear''' , clip_sample=__A , )
assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps
# shared batches for DDPM and DDIM
set_seed(0 )
_A = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(__A ) for _ in range(4 )]
_A = [torch.randn((4, 3, 32, 32) ).to(__A ) for _ in range(4 )]
_A = [torch.randint(0 , 10_00 , (4,) ).long().to(__A ) for _ in range(4 )]
# train with a DDPM scheduler
_A ,_A = self.get_model_optimizer(resolution=32 )
model.train().to(__A )
for i in range(4 ):
optimizer.zero_grad()
_A = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] )
_A = model(__A , timesteps[i] ).sample
_A = torch.nn.functional.mse_loss(__A , noise[i] )
loss.backward()
optimizer.step()
del model, optimizer
# recreate the model and optimizer, and retry with DDIM
_A ,_A = self.get_model_optimizer(resolution=32 )
model.train().to(__A )
for i in range(4 ):
optimizer.zero_grad()
_A = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] )
_A = model(__A , timesteps[i] ).sample
_A = torch.nn.functional.mse_loss(__A , noise[i] )
loss.backward()
optimizer.step()
del model, optimizer
self.assertTrue(torch.allclose(__A , __A , atol=1e-5 ) )
self.assertTrue(torch.allclose(__A , __A , atol=1e-5 ) )
| 707 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__A = {
'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MegaForCausalLM',
'MegaForMaskedLM',
'MegaForMultipleChoice',
'MegaForQuestionAnswering',
'MegaForSequenceClassification',
'MegaForTokenClassification',
'MegaModel',
'MegaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
__A = {
'configuration_ernie': ['ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieConfig', 'ErnieOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST',
'ErnieForCausalLM',
'ErnieForMaskedLM',
'ErnieForMultipleChoice',
'ErnieForNextSentencePrediction',
'ErnieForPreTraining',
'ErnieForQuestionAnswering',
'ErnieForSequenceClassification',
'ErnieForTokenClassification',
'ErnieModel',
'ErniePreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 708 |
import itertools
import string
from collections.abc import Generator, Iterable
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = iter(_lowercase )
while True:
_A = tuple(itertools.islice(_lowercase , _lowercase ) )
if not chunk:
return
yield chunk
def __A ( _lowercase ):
'''simple docstring'''
_A = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] )
_A = ''''''
if len(_lowercase ) < 2:
return dirty
for i in range(len(_lowercase ) - 1 ):
clean += dirty[i]
if dirty[i] == dirty[i + 1]:
clean += "X"
clean += dirty[-1]
if len(_lowercase ) & 1:
clean += "X"
return clean
def __A ( _lowercase ):
'''simple docstring'''
_A = '''ABCDEFGHIKLMNOPQRSTUVWXYZ'''
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
_A = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(_lowercase )
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(_lowercase )
return table
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = prepare_input(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
ciphertext += table[rowa * 5 + (cola + 1) % 5]
ciphertext += table[rowa * 5 + (cola + 1) % 5]
elif cola == cola:
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
else: # rectangle
ciphertext += table[rowa * 5 + cola]
ciphertext += table[rowa * 5 + cola]
return ciphertext
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = generate_table(_lowercase )
_A = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(_lowercase , 2 ):
_A ,_A = divmod(table.index(_lowercase ) , 5 )
_A ,_A = divmod(table.index(_lowercase ) , 5 )
if rowa == rowa:
plaintext += table[rowa * 5 + (cola - 1) % 5]
plaintext += table[rowa * 5 + (cola - 1) % 5]
elif cola == cola:
plaintext += table[((rowa - 1) % 5) * 5 + cola]
plaintext += table[((rowa - 1) % 5) * 5 + cola]
else: # rectangle
plaintext += table[rowa * 5 + cola]
plaintext += table[rowa * 5 + cola]
return plaintext
| 62 | 0 |
def __A ( _lowercase : int = 1_00 ):
'''simple docstring'''
_A = (n * (n + 1) // 2) ** 2
_A = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(f'{solution() = }')
| 709 |
import gc
import unittest
from transformers import CTRLConfig, 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, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Tuple , __A: Any , __A: List[Any]=14 , __A: Dict=7 , __A: List[str]=True , __A: Tuple=True , __A: Union[str, Any]=True , __A: List[Any]=True , __A: Optional[int]=True , __A: Tuple=99 , __A: Optional[Any]=32 , __A: List[str]=5 , __A: Dict=4 , __A: str=37 , __A: Dict="gelu" , __A: List[str]=0.1 , __A: str=0.1 , __A: Any=5_12 , __A: Union[str, Any]=16 , __A: List[Any]=2 , __A: Tuple=0.02 , __A: Tuple=3 , __A: Union[str, Any]=4 , __A: Any=None , ) -> Optional[Any]:
_A = parent
_A = batch_size
_A = seq_length
_A = is_training
_A = use_token_type_ids
_A = use_input_mask
_A = use_labels
_A = use_mc_token_ids
_A = vocab_size
_A = hidden_size
_A = num_hidden_layers
_A = num_attention_heads
_A = intermediate_size
_A = hidden_act
_A = hidden_dropout_prob
_A = attention_probs_dropout_prob
_A = max_position_embeddings
_A = type_vocab_size
_A = type_sequence_label_size
_A = initializer_range
_A = num_labels
_A = num_choices
_A = scope
_A = self.vocab_size - 1
def __A ( self: Optional[int] ) -> Union[str, Any]:
_A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_A = None
if self.use_input_mask:
_A = random_attention_mask([self.batch_size, self.seq_length] )
_A = None
if self.use_token_type_ids:
_A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_A = None
if self.use_mc_token_ids:
_A = ids_tensor([self.batch_size, self.num_choices] , self.seq_length )
_A = None
_A = None
_A = None
if self.use_labels:
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_A = ids_tensor([self.batch_size] , self.num_choices )
_A = self.get_config()
_A = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
token_type_ids,
mc_token_ids,
sequence_labels,
token_labels,
choice_labels,
)
def __A ( self: Optional[int] ) -> List[Any]:
return CTRLConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , )
def __A ( self: Union[str, Any] , __A: Union[str, Any] , __A: Dict , __A: Optional[int] , __A: List[str] , __A: List[str] , *__A: Optional[int] ) -> Optional[Any]:
_A = CTRLModel(config=__A )
model.to(__A )
model.eval()
model(__A , token_type_ids=__A , head_mask=__A )
model(__A , token_type_ids=__A )
_A = model(__A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(len(result.past_key_values ) , config.n_layer )
def __A ( self: Optional[Any] , __A: List[str] , __A: Dict , __A: List[Any] , __A: List[Any] , __A: Any , *__A: Any ) -> str:
_A = CTRLLMHeadModel(__A )
model.to(__A )
model.eval()
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __A ( self: Optional[int] ) -> Dict:
_A = self.prepare_config_and_inputs()
(
(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,(
_A
) ,
) = config_and_inputs
_A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}
return config, inputs_dict
def __A ( self: List[str] , __A: Dict , __A: Dict , __A: Tuple , __A: List[Any] , *__A: Optional[int] ) -> Any:
_A = self.num_labels
_A = CTRLForSequenceClassification(__A )
model.to(__A )
model.eval()
_A = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_A = model(__A , token_type_ids=__A , labels=__A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
A_ = (CTRLLMHeadModel,) if is_torch_available() else ()
A_ = (
{
"feature-extraction": CTRLModel,
"text-classification": CTRLForSequenceClassification,
"text-generation": CTRLLMHeadModel,
"zero-shot": CTRLForSequenceClassification,
}
if is_torch_available()
else {}
)
A_ = True
A_ = False
A_ = False
def __A ( self: Any , __A: List[Any] , __A: int , __A: Optional[Any] , __A: Optional[int] , __A: List[Any] ) -> List[str]:
if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
# config could not be created.
return True
return False
def __A ( self: Any ) -> Union[str, Any]:
_A = CTRLModelTester(self )
_A = ConfigTester(self , config_class=__A , n_embd=37 )
def __A ( self: Optional[int] ) -> List[Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
def __A ( self: Dict ) -> Any:
self.config_tester.run_common_tests()
def __A ( self: str ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_ctrl_model(*__A )
def __A ( self: List[str] ) -> Any:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head_model(*__A )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: Optional[Any] ) -> int:
pass
@slow
def __A ( self: Tuple ) -> Dict:
for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_A = CTRLModel.from_pretrained(__A )
self.assertIsNotNone(__A )
@unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :)
def __A ( self: Any ) -> Union[str, Any]:
pass
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: int ) -> Union[str, Any]:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
@slow
def __A ( self: Any ) -> Any:
_A = CTRLLMHeadModel.from_pretrained('''ctrl''' )
model.to(__A )
_A = torch.tensor(
[[1_18_59, 0, 16_11, 8]] , dtype=torch.long , device=__A ) # Legal the president is
_A = [
1_18_59,
0,
16_11,
8,
5,
1_50,
2_64_49,
2,
19,
3_48,
4_69,
3,
25_95,
48,
2_07_40,
24_65_33,
24_65_33,
19,
30,
5,
] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a
_A = model.generate(__A , do_sample=__A )
self.assertListEqual(output_ids[0].tolist() , __A )
| 62 | 0 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = tempfile.mkdtemp()
# fmt: off
_A = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
# fmt: on
_A = 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] ) )
_A = {
'''do_resize''': True,
'''size''': {'''height''': 18, '''width''': 18},
'''do_normalize''': True,
'''image_mean''': [0.5, 0.5, 0.5],
'''image_std''': [0.5, 0.5, 0.5],
}
_A = os.path.join(self.tmpdirname , __A )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(__A , __A )
def __A ( self: List[Any] , **__A: Any ) -> List[str]:
return BertTokenizer.from_pretrained(self.tmpdirname , **__A )
def __A ( self: int , **__A: List[str] ) -> Optional[Any]:
return ViTImageProcessor.from_pretrained(self.tmpdirname , **__A )
def __A ( self: Union[str, Any] ) -> Tuple:
shutil.rmtree(self.tmpdirname )
def __A ( self: Optional[int] ) -> Dict:
_A = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
_A = [Image.fromarray(np.moveaxis(__A , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def __A ( self: Any ) -> Dict:
_A = self.get_tokenizer()
_A = self.get_image_processor()
_A = VisionTextDualEncoderProcessor(tokenizer=__A , image_processor=__A )
processor.save_pretrained(self.tmpdirname )
_A = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , __A )
def __A ( self: Union[str, Any] ) -> int:
_A = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
_A = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
_A = self.get_image_processor(do_normalize=__A , padding_value=1.0 )
_A = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__A , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , __A )
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = self.get_image_processor()
_A = self.get_tokenizer()
_A = VisionTextDualEncoderProcessor(tokenizer=__A , image_processor=__A )
_A = self.prepare_image_inputs()
_A = image_processor(__A , return_tensors='''np''' )
_A = processor(images=__A , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def __A ( self: int ) -> List[str]:
_A = self.get_image_processor()
_A = self.get_tokenizer()
_A = VisionTextDualEncoderProcessor(tokenizer=__A , image_processor=__A )
_A = '''lower newer'''
_A = processor(text=__A )
_A = tokenizer(__A )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def __A ( self: Optional[int] ) -> Any:
_A = self.get_image_processor()
_A = self.get_tokenizer()
_A = VisionTextDualEncoderProcessor(tokenizer=__A , image_processor=__A )
_A = '''lower newer'''
_A = self.prepare_image_inputs()
_A = processor(text=__A , images=__A )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with self.assertRaises(__A ):
processor()
def __A ( self: Union[str, Any] ) -> Union[str, Any]:
_A = self.get_image_processor()
_A = self.get_tokenizer()
_A = VisionTextDualEncoderProcessor(tokenizer=__A , image_processor=__A )
_A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
_A = processor.batch_decode(__A )
_A = tokenizer.batch_decode(__A )
self.assertListEqual(__A , __A )
def __A ( self: Optional[int] ) -> Dict:
_A = self.get_image_processor()
_A = self.get_tokenizer()
_A = VisionTextDualEncoderProcessor(tokenizer=__A , image_processor=__A )
_A = '''lower newer'''
_A = self.prepare_image_inputs()
_A = processor(text=__A , images=__A )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 710 |
__A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
__A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = []
for neighbour in graph[vert]:
if not visited[neighbour]:
order += topology_sort(_lowercase , _lowercase , _lowercase )
order.append(_lowercase )
return order
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = True
_A = [vert]
for neighbour in reversed_graph[vert]:
if not visited[neighbour]:
component += find_components(_lowercase , _lowercase , _lowercase )
return component
def __A ( _lowercase ):
'''simple docstring'''
_A = len(_lowercase ) * [False]
_A = {vert: [] for vert in range(len(_lowercase ) )}
for vert, neighbours in graph.items():
for neighbour in neighbours:
reversed_graph[neighbour].append(_lowercase )
_A = []
for i, was_visited in enumerate(_lowercase ):
if not was_visited:
order += topology_sort(_lowercase , _lowercase , _lowercase )
_A = []
_A = len(_lowercase ) * [False]
for i in range(len(_lowercase ) ):
_A = order[len(_lowercase ) - i - 1]
if not visited[vert]:
_A = find_components(_lowercase , _lowercase , _lowercase )
components_list.append(_lowercase )
return components_list
| 62 | 0 |
import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel
from ...utils import logging
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = CLIPConfig
A_ = ["CLIPEncoderLayer"]
def __init__( self: Optional[Any] , __A: CLIPConfig ) -> Any:
super().__init__(__A )
_A = CLIPVisionModelWithProjection(config.vision_config )
_A = nn.Linear(config.vision_config.projection_dim , 1 )
_A = nn.Linear(config.vision_config.projection_dim , 1 )
@torch.no_grad()
def __A ( self: str , __A: Any , __A: Optional[int] , __A: Tuple=0.5 , __A: List[Any]=0.5 ) -> int:
_A = self.vision_model(__A )[0]
_A = self.p_head(__A )
_A = nsfw_detected.flatten()
_A = nsfw_detected > p_threshold
_A = nsfw_detected.tolist()
if any(__A ):
logger.warning(
'''Potential NSFW content was detected in one or more images. A black image will be returned instead.'''
''' Try again with a different prompt and/or seed.''' )
for idx, nsfw_detected_ in enumerate(__A ):
if nsfw_detected_:
_A = np.zeros(images[idx].shape )
_A = self.w_head(__A )
_A = watermark_detected.flatten()
_A = watermark_detected > w_threshold
_A = watermark_detected.tolist()
if any(__A ):
logger.warning(
'''Potential watermarked content was detected in one or more images. A black image will be returned instead.'''
''' Try again with a different prompt and/or seed.''' )
for idx, watermark_detected_ in enumerate(__A ):
if watermark_detected_:
_A = np.zeros(images[idx].shape )
return images, nsfw_detected, watermark_detected
| 711 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
global f # a global dp table for knapsack
if f[i][j] < 0:
if j < wt[i - 1]:
_A = mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase )
else:
_A = max(
mf_knapsack(i - 1 , _lowercase , _lowercase , _lowercase ) , mf_knapsack(i - 1 , _lowercase , _lowercase , j - wt[i - 1] ) + val[i - 1] , )
_A = val
return f[i][j]
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = [[0] * (w + 1) for _ in range(n + 1 )]
for i in range(1 , n + 1 ):
for w_ in range(1 , w + 1 ):
if wt[i - 1] <= w_:
_A = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] )
else:
_A = dp[i - 1][w_]
return dp[n][w_], dp
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if not (isinstance(_lowercase , (list, tuple) ) and isinstance(_lowercase , (list, tuple) )):
raise ValueError(
'''Both the weights and values vectors must be either lists or tuples''' )
_A = len(_lowercase )
if num_items != len(_lowercase ):
_A = (
'''The number of weights must be the same as the number of values.\n'''
f"""But got {num_items} weights and {len(_lowercase )} values"""
)
raise ValueError(_lowercase )
for i in range(_lowercase ):
if not isinstance(wt[i] , _lowercase ):
_A = (
'''All weights must be integers but got weight of '''
f"""type {type(wt[i] )} at index {i}"""
)
raise TypeError(_lowercase )
_A ,_A = knapsack(_lowercase , _lowercase , _lowercase , _lowercase )
_A = set()
_construct_solution(_lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
return optimal_val, example_optional_set
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if i > 0 and j > 0:
if dp[i - 1][j] == dp[i][j]:
_construct_solution(_lowercase , _lowercase , i - 1 , _lowercase , _lowercase )
else:
optimal_set.add(_lowercase )
_construct_solution(_lowercase , _lowercase , i - 1 , j - wt[i - 1] , _lowercase )
if __name__ == "__main__":
__A = [3, 2, 4, 4]
__A = [4, 3, 2, 3]
__A = 4
__A = 6
__A = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)]
__A , __A = knapsack(w, wt, val, n)
print(optimal_solution)
print(mf_knapsack(n, wt, val, w)) # switched the n and w
# testing the dynamic programming problem with example
# the optimal subset for the above example are items 3 and 4
__A , __A = knapsack_with_example_solution(w, wt, val)
assert optimal_solution == 8
assert optimal_subset == {3, 4}
print('optimal_value = ', optimal_solution)
print('An optimal subset corresponding to the optimal value', optimal_subset)
| 62 | 0 |
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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = PriorTransformer
A_ = "hidden_states"
@property
def __A ( self: List[str] ) -> Dict:
_A = 4
_A = 8
_A = 7
_A = floats_tensor((batch_size, embedding_dim) ).to(__A )
_A = floats_tensor((batch_size, embedding_dim) ).to(__A )
_A = floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(__A )
return {
"hidden_states": hidden_states,
"timestep": 2,
"proj_embedding": proj_embedding,
"encoder_hidden_states": encoder_hidden_states,
}
def __A ( self: Union[str, Any] , __A: List[Any]=0 ) -> str:
torch.manual_seed(__A )
_A = 4
_A = 8
_A = 7
_A = torch.randn((batch_size, embedding_dim) ).to(__A )
_A = torch.randn((batch_size, embedding_dim) ).to(__A )
_A = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(__A )
return {
"hidden_states": hidden_states,
"timestep": 2,
"proj_embedding": proj_embedding,
"encoder_hidden_states": encoder_hidden_states,
}
@property
def __A ( self: Dict ) -> int:
return (4, 8)
@property
def __A ( self: Any ) -> Dict:
return (4, 8)
def __A ( self: List[Any] ) -> List[str]:
_A = {
'''num_attention_heads''': 2,
'''attention_head_dim''': 4,
'''num_layers''': 2,
'''embedding_dim''': 8,
'''num_embeddings''': 7,
'''additional_embeddings''': 4,
}
_A = self.dummy_input
return init_dict, inputs_dict
def __A ( self: Optional[Any] ) -> str:
_A ,_A = PriorTransformer.from_pretrained(
'''hf-internal-testing/prior-dummy''' , output_loading_info=__A )
self.assertIsNotNone(__A )
self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 )
model.to(__A )
_A = model(**self.dummy_input )[0]
assert hidden_states is not None, "Make sure output is not None"
def __A ( self: Tuple ) -> List[Any]:
_A ,_A = self.prepare_init_args_and_inputs_for_common()
_A = self.model_class(**__A )
_A = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_A = [*signature.parameters.keys()]
_A = ['''hidden_states''', '''timestep''']
self.assertListEqual(arg_names[:2] , __A )
def __A ( self: Optional[Any] ) -> int:
_A = PriorTransformer.from_pretrained('''hf-internal-testing/prior-dummy''' )
_A = model.to(__A )
if hasattr(__A , '''set_default_attn_processor''' ):
model.set_default_attn_processor()
_A = self.get_dummy_seed_input()
with torch.no_grad():
_A = model(**__A )[0]
_A = output[0, :5].flatten().cpu()
print(__A )
# 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.
_A = torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239] )
self.assertTrue(torch_all_close(__A , __A , rtol=1e-2 ) )
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: int , __A: Optional[Any]=1 , __A: List[Any]=7_68 , __A: List[str]=77 , __A: List[Any]=0 ) -> Any:
torch.manual_seed(__A )
_A = batch_size
_A = embedding_dim
_A = num_embeddings
_A = torch.randn((batch_size, embedding_dim) ).to(__A )
_A = torch.randn((batch_size, embedding_dim) ).to(__A )
_A = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(__A )
return {
"hidden_states": hidden_states,
"timestep": 2,
"proj_embedding": proj_embedding,
"encoder_hidden_states": encoder_hidden_states,
}
def __A ( self: Optional[Any] ) -> Any:
# clean up the VRAM after each test
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: Any , __A: Tuple , __A: int ) -> Dict:
_A = PriorTransformer.from_pretrained('''kandinsky-community/kandinsky-2-1-prior''' , subfolder='''prior''' )
model.to(__A )
_A = self.get_dummy_seed_input(seed=__A )
with torch.no_grad():
_A = model(**__A )[0]
assert list(sample.shape ) == [1, 7_68]
_A = sample[0, :8].flatten().cpu()
print(__A )
_A = torch.tensor(__A )
assert torch_all_close(__A , __A , atol=1e-3 )
| 712 |
def __A ( _lowercase = 1_00_00_00 ):
'''simple docstring'''
_A = 1
_A = 1
_A = {1: 1}
for inputa in range(2 , _lowercase ):
_A = 0
_A = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_A = (3 * number) + 1
counter += 1
if inputa not in counters:
_A = counter
if counter > pre_counter:
_A = inputa
_A = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 62 | 0 |
import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from requests.exceptions import HTTPError
from transformers.utils import (
CONFIG_NAME,
FLAX_WEIGHTS_NAME,
TF2_WEIGHTS_NAME,
TRANSFORMERS_CACHE,
WEIGHTS_NAME,
cached_file,
get_file_from_repo,
has_file,
)
__A = 'hf-internal-testing/tiny-random-bert'
__A = os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
__A = '9b8c223d42b2188cb49d29af482996f9d0f3e5a6'
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: Union[str, Any] ) -> Optional[Any]:
_A = cached_file(__A , __A )
# Should have downloaded the file in here
self.assertTrue(os.path.isdir(__A ) )
# Cache should contain at least those three subfolders:
for subfolder in ["blobs", "refs", "snapshots"]:
self.assertTrue(os.path.isdir(os.path.join(__A , __A ) ) )
with open(os.path.join(__A , '''refs''' , '''main''' ) ) as f:
_A = f.read()
self.assertEqual(__A , os.path.join(__A , '''snapshots''' , __A , __A ) )
self.assertTrue(os.path.isfile(__A ) )
# File is cached at the same place the second time.
_A = cached_file(__A , __A )
self.assertEqual(__A , __A )
# Using a specific revision to test the full commit hash.
_A = cached_file(__A , __A , revision='''9b8c223''' )
self.assertEqual(__A , os.path.join(__A , '''snapshots''' , __A , __A ) )
def __A ( self: Optional[Any] ) -> Dict:
with self.assertRaisesRegex(__A , '''is not a valid model identifier''' ):
_A = cached_file('''tiny-random-bert''' , __A )
with self.assertRaisesRegex(__A , '''is not a valid git identifier''' ):
_A = cached_file(__A , __A , revision='''aaaa''' )
with self.assertRaisesRegex(__A , '''does not appear to have a file named''' ):
_A = cached_file(__A , '''conf''' )
def __A ( self: Dict ) -> List[str]:
with self.assertRaisesRegex(__A , '''does not appear to have a file named''' ):
_A = cached_file(__A , '''conf''' )
with open(os.path.join(__A , '''refs''' , '''main''' ) ) as f:
_A = f.read()
self.assertTrue(os.path.isfile(os.path.join(__A , '''.no_exist''' , __A , '''conf''' ) ) )
_A = cached_file(__A , '''conf''' , _raise_exceptions_for_missing_entries=__A )
self.assertIsNone(__A )
_A = cached_file(__A , '''conf''' , local_files_only=__A , _raise_exceptions_for_missing_entries=__A )
self.assertIsNone(__A )
_A = mock.Mock()
_A = 5_00
_A = {}
_A = HTTPError
_A = {}
# 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 = cached_file(__A , '''conf''' , _raise_exceptions_for_connection_errors=__A )
self.assertIsNone(__A )
# This check we did call the fake head request
mock_head.assert_called()
def __A ( self: Optional[Any] ) -> Dict:
self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __A ) )
self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __A ) )
self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __A ) )
def __A ( self: Tuple ) -> Tuple:
# `get_file_from_repo` returns None if the file does not exist
self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) )
# The function raises if the repository does not exist.
with self.assertRaisesRegex(__A , '''is not a valid model identifier''' ):
get_file_from_repo('''bert-base-case''' , __A )
# The function raises if the revision does not exist.
with self.assertRaisesRegex(__A , '''is not a valid git identifier''' ):
get_file_from_repo('''bert-base-cased''' , __A , revision='''ahaha''' )
_A = get_file_from_repo('''bert-base-cased''' , __A )
# The name is the cached name which is not very easy to test, so instead we load the content.
_A = json.loads(open(__A , '''r''' ).read() )
self.assertEqual(config['''hidden_size'''] , 7_68 )
def __A ( self: str ) -> Tuple:
with tempfile.TemporaryDirectory() as tmp_dir:
_A = Path(__A ) / '''a.txt'''
filename.touch()
self.assertEqual(get_file_from_repo(__A , '''a.txt''' ) , str(__A ) )
self.assertIsNone(get_file_from_repo(__A , '''b.txt''' ) )
| 713 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = word.split()
def justify(_lowercase , _lowercase , _lowercase ) -> str:
_A = max_width - width
_A = len(_lowercase )
if len(_lowercase ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_A = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_A = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_A = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_lowercase ):
num_spaces_between_words_list[i] += 1
_A = []
for i in range(_lowercase ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * ''' ''' )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_lowercase )
_A = []
_A = []
_A = 0
for word in words:
if width + len(_lowercase ) + len(_lowercase ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_lowercase )
width += len(_lowercase )
else:
# justify the line and add it to result
answer.append(justify(_lowercase , _lowercase , _lowercase ) )
# reset new line and new width
_A ,_A = [word], len(_lowercase )
_A = max_width - width - len(_lowercase )
answer.append(''' '''.join(_lowercase ) + (remaining_spaces + 1) * ''' ''' )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 62 | 0 |
import gc
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
ClapTextConfig,
ClapTextModelWithProjection,
RobertaTokenizer,
SpeechTaHifiGan,
SpeechTaHifiGanConfig,
)
from diffusers import (
AudioLDMPipeline,
AutoencoderKL,
DDIMScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = AudioLDMPipeline
A_ = TEXT_TO_AUDIO_PARAMS
A_ = TEXT_TO_AUDIO_BATCH_PARAMS
A_ = frozenset(
[
"num_inference_steps",
"num_waveforms_per_prompt",
"generator",
"latents",
"output_type",
"return_dict",
"callback",
"callback_steps",
] )
def __A ( self: List[Any] ) -> Dict:
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, 64) , class_embed_type='''simple_projection''' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=__A , )
_A = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=__A , set_alpha_to_one=__A , )
torch.manual_seed(0 )
_A = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , )
torch.manual_seed(0 )
_A = ClapTextConfig(
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 , projection_dim=32 , )
_A = ClapTextModelWithProjection(__A )
_A = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' , model_max_length=77 )
_A = SpeechTaHifiGanConfig(
model_in_dim=8 , sampling_rate=1_60_00 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=__A , )
_A = SpeechTaHifiGan(__A )
_A = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''vocoder''': vocoder,
}
return components
def __A ( self: Optional[int] , __A: List[str] , __A: List[str]=0 ) -> Tuple:
if str(__A ).startswith('''mps''' ):
_A = torch.manual_seed(__A )
else:
_A = torch.Generator(device=__A ).manual_seed(__A )
_A = {
'''prompt''': '''A hammer hitting a wooden surface''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 6.0,
}
return inputs
def __A ( self: int ) -> Dict:
_A = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_A = self.get_dummy_components()
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = self.get_dummy_inputs(__A )
_A = audioldm_pipe(**__A )
_A = output.audios[0]
assert audio.ndim == 1
assert len(__A ) == 2_56
_A = audio[:10]
_A = np.array(
[-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033] )
assert np.abs(audio_slice - expected_slice ).max() < 1e-2
def __A ( self: Optional[Any] ) -> Tuple:
_A = self.get_dummy_components()
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = self.get_dummy_inputs(__A )
_A = 3 * [inputs['''prompt''']]
# forward
_A = audioldm_pipe(**__A )
_A = output.audios[0]
_A = self.get_dummy_inputs(__A )
_A = 3 * [inputs.pop('''prompt''' )]
_A = audioldm_pipe.tokenizer(
__A , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__A , return_tensors='''pt''' , )
_A = text_inputs['''input_ids'''].to(__A )
_A = audioldm_pipe.text_encoder(
__A , )
_A = prompt_embeds.text_embeds
# additional L_2 normalization over each hidden-state
_A = F.normalize(__A , dim=-1 )
_A = prompt_embeds
# forward
_A = audioldm_pipe(**__A )
_A = output.audios[0]
assert np.abs(audio_a - audio_a ).max() < 1e-2
def __A ( self: Union[str, Any] ) -> Optional[Any]:
_A = self.get_dummy_components()
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = self.get_dummy_inputs(__A )
_A = 3 * ['''this is a negative prompt''']
_A = negative_prompt
_A = 3 * [inputs['''prompt''']]
# forward
_A = audioldm_pipe(**__A )
_A = output.audios[0]
_A = self.get_dummy_inputs(__A )
_A = 3 * [inputs.pop('''prompt''' )]
_A = []
for p in [prompt, negative_prompt]:
_A = audioldm_pipe.tokenizer(
__A , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__A , return_tensors='''pt''' , )
_A = text_inputs['''input_ids'''].to(__A )
_A = audioldm_pipe.text_encoder(
__A , )
_A = text_embeds.text_embeds
# additional L_2 normalization over each hidden-state
_A = F.normalize(__A , dim=-1 )
embeds.append(__A )
_A ,_A = embeds
# forward
_A = audioldm_pipe(**__A )
_A = output.audios[0]
assert np.abs(audio_a - audio_a ).max() < 1e-2
def __A ( self: int ) -> str:
_A = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_A = self.get_dummy_components()
_A = PNDMScheduler(skip_prk_steps=__A )
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = self.get_dummy_inputs(__A )
_A = '''egg cracking'''
_A = audioldm_pipe(**__A , negative_prompt=__A )
_A = output.audios[0]
assert audio.ndim == 1
assert len(__A ) == 2_56
_A = audio[:10]
_A = np.array(
[-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032] )
assert np.abs(audio_slice - expected_slice ).max() < 1e-2
def __A ( self: Optional[Any] ) -> Union[str, Any]:
_A = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_A = self.get_dummy_components()
_A = PNDMScheduler(skip_prk_steps=__A )
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = '''A hammer hitting a wooden surface'''
# test num_waveforms_per_prompt=1 (default)
_A = audioldm_pipe(__A , num_inference_steps=2 ).audios
assert audios.shape == (1, 2_56)
# test num_waveforms_per_prompt=1 (default) for batch of prompts
_A = 2
_A = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios
assert audios.shape == (batch_size, 2_56)
# test num_waveforms_per_prompt for single prompt
_A = 2
_A = audioldm_pipe(__A , num_inference_steps=2 , num_waveforms_per_prompt=__A ).audios
assert audios.shape == (num_waveforms_per_prompt, 2_56)
# test num_waveforms_per_prompt for batch of prompts
_A = 2
_A = audioldm_pipe(
[prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=__A ).audios
assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_56)
def __A ( self: Union[str, Any] ) -> Any:
_A = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_A = self.get_dummy_components()
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = audioldm_pipe.vocoder.config.sampling_rate
_A = self.get_dummy_inputs(__A )
_A = audioldm_pipe(audio_length_in_s=0.016 , **__A )
_A = output.audios[0]
assert audio.ndim == 1
assert len(__A ) / vocoder_sampling_rate == 0.016
_A = audioldm_pipe(audio_length_in_s=0.032 , **__A )
_A = output.audios[0]
assert audio.ndim == 1
assert len(__A ) / vocoder_sampling_rate == 0.032
def __A ( self: str ) -> Any:
_A = self.get_dummy_components()
_A = AudioLDMPipeline(**__A )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = ['''hey''']
_A = audioldm_pipe(__A , num_inference_steps=1 )
_A = output.audios.shape
assert audio_shape == (1, 2_56)
_A = audioldm_pipe.vocoder.config
config.model_in_dim *= 2
_A = SpeechTaHifiGan(__A ).to(__A )
_A = audioldm_pipe(__A , num_inference_steps=1 )
_A = output.audios.shape
# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
assert audio_shape == (1, 2_56)
def __A ( self: Union[str, Any] ) -> Optional[Any]:
self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__A )
def __A ( self: int ) -> Union[str, Any]:
self._test_inference_batch_single_identical(test_mean_pixel_difference=__A )
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def __A ( self: Dict ) -> Optional[int]:
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__A )
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __A ( self: List[str] ) -> Optional[int]:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self: int , __A: Optional[Any] , __A: str="cpu" , __A: Dict=torch.floataa , __A: Union[str, Any]=0 ) -> Any:
_A = torch.Generator(device=__A ).manual_seed(__A )
_A = np.random.RandomState(__A ).standard_normal((1, 8, 1_28, 16) )
_A = torch.from_numpy(__A ).to(device=__A , dtype=__A )
_A = {
'''prompt''': '''A hammer hitting a wooden surface''',
'''latents''': latents,
'''generator''': generator,
'''num_inference_steps''': 3,
'''guidance_scale''': 2.5,
}
return inputs
def __A ( self: Any ) -> int:
_A = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = self.get_inputs(__A )
_A = 25
_A = audioldm_pipe(**__A ).audios[0]
assert audio.ndim == 1
assert len(__A ) == 8_19_20
_A = audio[7_72_30:7_72_40]
_A = np.array(
[-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315] )
_A = np.abs(expected_slice - audio_slice ).max()
assert max_diff < 1e-2
def __A ( self: Optional[Any] ) -> str:
_A = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' )
_A = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config )
_A = audioldm_pipe.to(__A )
audioldm_pipe.set_progress_bar_config(disable=__A )
_A = self.get_inputs(__A )
_A = audioldm_pipe(**__A ).audios[0]
assert audio.ndim == 1
assert len(__A ) == 8_19_20
_A = audio[2_77_80:2_77_90]
_A = np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212] )
_A = np.abs(expected_slice - audio_slice ).max()
assert max_diff < 3e-2
| 714 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = '\\n Text data.\n Second line of data.'
__A = 'file'
@pytest.fixture(scope='''session''' )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''')
_A = bytes(_lowercase , '''utf-8''' )
with zstd.open(_lowercase , '''wb''' ) as f:
f.write(_lowercase )
return path
@pytest.fixture
def __A ( _lowercase ):
'''simple docstring'''
with open(os.path.join(tmpfs.local_root_dir , _lowercase ) , '''w''' ) as f:
f.write(_lowercase )
return FILE_PATH
@pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
_A = input_paths[compression_format]
_A = tmp_path / '''cache'''
_A = DownloadConfig(cache_dir=_lowercase , extract_compressed_file=_lowercase )
_A = cached_path(_lowercase , download_config=_lowercase )
with open(_lowercase ) as f:
_A = f.read()
with open(_lowercase ) as f:
_A = f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize('''default_extracted''' , [True, False] )
@pytest.mark.parametrize('''default_cache_dir''' , [True, False] )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = '''custom_cache'''
_A = '''custom_extracted_dir'''
_A = tmp_path / '''custom_extracted_path'''
if default_extracted:
_A = ('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
else:
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , _lowercase )
monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(_lowercase ) )
_A = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_A = xz_file
_A = (
DownloadConfig(extract_compressed_file=_lowercase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowercase )
)
_A = cached_path(_lowercase , download_config=_lowercase )
assert Path(_lowercase ).parent.parts[-2:] == expected
def __A ( _lowercase ):
'''simple docstring'''
_A = str(Path(_lowercase ).resolve() )
assert cached_path(_lowercase ) == text_file
# relative path
_A = str(Path(_lowercase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowercase ) == text_file
def __A ( _lowercase ):
'''simple docstring'''
_A = str(tmp_path.resolve() / '''__missing_file__.txt''' )
with pytest.raises(_lowercase ):
cached_path(_lowercase )
# relative path
_A = '''./__missing_file__.txt'''
with pytest.raises(_lowercase ):
cached_path(_lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = get_from_cache(f"""tmp://{tmpfs_file}""" )
with open(_lowercase ) as f:
_A = f.read()
assert output_file_content == FILE_CONTENT
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( ):
'''simple docstring'''
with pytest.raises(_lowercase ):
cached_path('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
http_get('''https://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
http_head('''https://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
ftp_get('''ftp://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
ftp_head('''ftp://huggingface.co''' )
@patch('''datasets.config.HF_DATASETS_OFFLINE''' , _lowercase )
def __A ( _lowercase ):
'''simple docstring'''
_A = tmp_path_factory.mktemp('''data''' ) / '''file.html'''
with pytest.raises(_lowercase ):
fsspec_get('''s3://huggingface.co''' , temp_file=_lowercase )
with pytest.raises(_lowercase ):
fsspec_head('''s3://huggingface.co''' )
| 62 | 0 |
'''simple docstring'''
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 __A ( _lowercase , _lowercase ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase )
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 __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_A = ParquetDatasetReader(_lowercase , cache_dir=_lowercase , keep_in_memory=_lowercase ).read()
_check_parquet_dataset(_lowercase , _lowercase )
@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 __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
_A = features.copy() if features else default_expected_features
_A = (
Features({feature: Value(_lowercase ) for feature, dtype in features.items()} ) if features is not None else None
)
_A = ParquetDatasetReader(_lowercase , features=_lowercase , cache_dir=_lowercase ).read()
_check_parquet_dataset(_lowercase , _lowercase )
@pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
_A = ParquetDatasetReader(_lowercase , cache_dir=_lowercase , split=_lowercase ).read()
_check_parquet_dataset(_lowercase , _lowercase )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize('''path_type''' , [str, list] )
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if issubclass(_lowercase , _lowercase ):
_A = parquet_path
elif issubclass(_lowercase , _lowercase ):
_A = [parquet_path]
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
_A = ParquetDatasetReader(_lowercase , cache_dir=_lowercase ).read()
_check_parquet_dataset(_lowercase , _lowercase )
def __A ( _lowercase , _lowercase , _lowercase=("train",) ):
'''simple docstring'''
assert isinstance(_lowercase , _lowercase )
for split in splits:
_A = 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 __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
_A = ParquetDatasetReader(
{'''train''': parquet_path} , cache_dir=_lowercase , keep_in_memory=_lowercase ).read()
_check_parquet_datasetdict(_lowercase , _lowercase )
@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 __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
_A = features.copy() if features else default_expected_features
_A = (
Features({feature: Value(_lowercase ) for feature, dtype in features.items()} ) if features is not None else None
)
_A = ParquetDatasetReader({'''train''': parquet_path} , features=_lowercase , cache_dir=_lowercase ).read()
_check_parquet_datasetdict(_lowercase , _lowercase )
@pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def __A ( _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if split:
_A = {split: parquet_path}
else:
_A = '''train'''
_A = {'''train''': parquet_path, '''test''': parquet_path}
_A = tmp_path / '''cache'''
_A = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
_A = ParquetDatasetReader(_lowercase , cache_dir=_lowercase ).read()
_check_parquet_datasetdict(_lowercase , _lowercase , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = ParquetDatasetWriter(_lowercase , tmp_path / '''foo.parquet''' )
assert writer.write() > 0
_A = pq.ParquetFile(tmp_path / '''foo.parquet''' )
_A = pf.read()
assert dataset.data.table == output_table
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = str(shared_datadir / '''test_image_rgb.jpg''' )
_A = {'''image''': [image_path]}
_A = Features({'''image''': Image()} )
_A = Dataset.from_dict(_lowercase , features=_lowercase )
_A = ParquetDatasetWriter(_lowercase , tmp_path / '''foo.parquet''' )
assert writer.write() > 0
_A = Dataset.from_parquet(str(tmp_path / '''foo.parquet''' ) )
assert dataset.features == reloaded_dataset.features
_A = ParquetDatasetReader(str(tmp_path / '''foo.parquet''' ) , streaming=_lowercase ).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 __A ( _lowercase , _lowercase ):
'''simple docstring'''
assert get_writer_batch_size(_lowercase ) == expected
| 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 |
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
_A = [1]
for i in range(2 , _lowercase ):
factorials.append(factorials[-1] * i )
assert 0 <= k < factorials[-1] * n, "k out of bounds"
_A = []
_A = list(range(_lowercase ) )
# Find permutation
while factorials:
_A = factorials.pop()
_A ,_A = divmod(_lowercase , _lowercase )
permutation.append(elements[number] )
elements.remove(elements[number] )
permutation.append(elements[0] )
return permutation
if __name__ == "__main__":
import doctest
doctest.testmod()
| 716 |
import flax.linen as nn
import jax
import jax.numpy as jnp
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: Tuple ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Dict , __A: Dict ) -> Tuple:
_A ,_A ,_A ,_A = hidden_states.shape
_A = jax.image.resize(
__A , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , )
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = jnp.floataa
def __A ( self: List[str] ) -> Tuple:
_A = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self: Union[str, Any] , __A: List[Any] ) -> Union[str, Any]:
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
_A = self.conv(__A )
return hidden_states
class SCREAMING_SNAKE_CASE ( nn.Module ):
"""simple docstring"""
A_ = 42
A_ = None
A_ = 0.0
A_ = None
A_ = jnp.floataa
def __A ( self: Dict ) -> Dict:
_A = self.in_channels if self.out_channels is None else self.out_channels
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = nn.Dense(__A , dtype=self.dtype )
_A = nn.GroupNorm(num_groups=32 , epsilon=1e-5 )
_A = nn.Dropout(self.dropout_prob )
_A = nn.Conv(
__A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_A = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
_A = None
if use_nin_shortcut:
_A = nn.Conv(
__A , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , )
def __call__( self: Dict , __A: List[Any] , __A: List[Any] , __A: Any=True ) -> List[Any]:
_A = hidden_states
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.conva(__A )
_A = self.time_emb_proj(nn.swish(__A ) )
_A = jnp.expand_dims(jnp.expand_dims(__A , 1 ) , 1 )
_A = hidden_states + temb
_A = self.norma(__A )
_A = nn.swish(__A )
_A = self.dropout(__A , __A )
_A = self.conva(__A )
if self.conv_shortcut is not None:
_A = self.conv_shortcut(__A )
return hidden_states + residual
| 62 | 0 |
import json
import logging
import os
import sys
from pathlib import Path
import finetune_rag
from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
TestCasePlus,
execute_subprocess_async,
require_ray,
require_torch_gpu,
require_torch_multi_gpu,
)
logging.basicConfig(level=logging.DEBUG)
__A = logging.getLogger()
__A = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
def __A ( self: Any , __A: Union[str, Any] ) -> Optional[Any]:
os.makedirs(__A , exist_ok=__A )
_A = {'''source''': '''What is love ?''', '''target''': '''life'''}
_A = {'''train''': 12, '''val''': 2, '''test''': 2}
for split in ["train", "test", "val"]:
for field in ["source", "target"]:
_A = '''\n'''.join([contents[field]] * n_lines[split] )
with open(os.path.join(__A , f"""{split}.{field}""" ) , '''w''' ) as f:
f.write(__A )
def __A ( self: Dict , __A: int , __A: str = "pytorch" ) -> Union[str, Any]:
_A = self.get_auto_remove_tmp_dir()
_A = os.path.join(__A , '''output''' )
_A = os.path.join(__A , '''data''' )
self._create_dummy_data(data_dir=__A )
_A = f"""
--data_dir {data_dir} \
--output_dir {output_dir} \
--model_name_or_path facebook/rag-sequence-base \
--model_type rag_sequence \
--do_train \
--do_predict \
--n_val -1 \
--val_check_interval 1.0 \
--train_batch_size 2 \
--eval_batch_size 1 \
--max_source_length 25 \
--max_target_length 25 \
--val_max_target_length 25 \
--test_max_target_length 25 \
--label_smoothing 0.1 \
--dropout 0.1 \
--attention_dropout 0.1 \
--weight_decay 0.001 \
--adam_epsilon 1e-08 \
--max_grad_norm 0.1 \
--lr_scheduler polynomial \
--learning_rate 3e-04 \
--num_train_epochs 1 \
--warmup_steps 4 \
--gradient_accumulation_steps 1 \
--distributed-port 8787 \
--use_dummy_dataset 1 \
--distributed_retriever {distributed_retriever} \
""".split()
if gpus > 0:
testargs.append(f"""--gpus={gpus}""" )
if is_apex_available():
testargs.append('''--fp16''' )
else:
testargs.append('''--gpus=0''' )
testargs.append('''--distributed_backend=ddp_cpu''' )
testargs.append('''--num_processes=2''' )
_A = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs
execute_subprocess_async(__A , env=self.get_env() )
_A = os.path.join(__A , '''metrics.json''' )
with open(__A ) as f:
_A = json.load(__A )
return result
@require_torch_gpu
def __A ( self: Any ) -> Any:
_A = self._run_finetune(gpus=1 )
self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
@require_torch_multi_gpu
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = self._run_finetune(gpus=2 )
self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
@require_torch_gpu
@require_ray
def __A ( self: str ) -> Tuple:
_A = self._run_finetune(gpus=1 , distributed_retriever='''ray''' )
self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
@require_torch_multi_gpu
@require_ray
def __A ( self: List[Any] ) -> Optional[int]:
_A = self._run_finetune(gpus=1 , distributed_retriever='''ray''' )
self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
| 717 |
def __A ( _lowercase ):
'''simple docstring'''
_A = [0] * len(_lowercase )
_A = []
_A = []
_A = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(_lowercase ) ):
if indegree[i] == 0:
queue.append(_lowercase )
while queue:
_A = queue.pop(0 )
cnt += 1
topo.append(_lowercase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(_lowercase )
if cnt != len(_lowercase ):
print('''Cycle exists''' )
else:
print(_lowercase )
# Adjacency List of Graph
__A = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 62 | 0 |
from collections import Counter
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
__A = datasets.load_iris()
__A = np.array(data['data'])
__A = np.array(data['target'])
__A = data['target_names']
__A , __A , __A , __A = train_test_split(X, y)
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
return np.linalg.norm(np.array(_lowercase ) - np.array(_lowercase ) )
def __A ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase=5 ):
'''simple docstring'''
_A = zip(_lowercase , _lowercase )
# List of distances of all points from the point to be classified
_A = []
for data_point in data:
_A = euclidean_distance(data_point[0] , _lowercase )
distances.append((distance, data_point[1]) )
# Choosing 'k' points with the least distances.
_A = [i[1] for i in sorted(_lowercase )[:k]]
# Most commonly occurring class among them
# is the class into which the point is classified
_A = Counter(_lowercase ).most_common(1 )[0][0]
return classes[result]
if __name__ == "__main__":
print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
| 718 |
import math
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 SchedulerMixin, SchedulerOutput
class SCREAMING_SNAKE_CASE ( snake_case , snake_case ):
"""simple docstring"""
A_ = 1
@register_to_config
def __init__( self: Any , __A: int = 10_00 , __A: Optional[Union[np.ndarray, List[float]]] = None ) -> List[str]:
# set `betas`, `alphas`, `timesteps`
self.set_timesteps(__A )
# standard deviation of the initial noise distribution
_A = 1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
_A = 4
# running values
_A = []
def __A ( self: str , __A: int , __A: Union[str, torch.device] = None ) -> int:
_A = num_inference_steps
_A = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
_A = torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
_A = torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
_A = torch.sin(steps * math.pi / 2 ) ** 2
_A = (1.0 - self.betas**2) ** 0.5
_A = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
_A = timesteps.to(__A )
_A = []
def __A ( self: Tuple , __A: torch.FloatTensor , __A: int , __A: torch.FloatTensor , __A: bool = True , ) -> Union[SchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
_A = (self.timesteps == timestep).nonzero().item()
_A = timestep_index + 1
_A = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(__A )
if len(self.ets ) == 1:
_A = self.ets[-1]
elif len(self.ets ) == 2:
_A = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
_A = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
_A = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
_A = self._get_prev_sample(__A , __A , __A , __A )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__A )
def __A ( self: Optional[int] , __A: torch.FloatTensor , *__A: Tuple , **__A: List[Any] ) -> torch.FloatTensor:
return sample
def __A ( self: List[str] , __A: Optional[Any] , __A: Optional[Any] , __A: Any , __A: List[Any] ) -> List[Any]:
_A = self.alphas[timestep_index]
_A = self.betas[timestep_index]
_A = self.alphas[prev_timestep_index]
_A = self.betas[prev_timestep_index]
_A = (sample - sigma * ets) / max(__A , 1e-8 )
_A = next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self: List[str] ) -> Dict:
return self.config.num_train_timesteps
| 62 | 0 |
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
__A = TypeVar('T')
class SCREAMING_SNAKE_CASE ( Generic[T] ):
"""simple docstring"""
A_ = 42 # Cache store of keys
A_ = 42 # References of the keys in cache
A_ = 10 # Maximum capacity of cache
def __init__( self: Optional[int] , __A: int ) -> None:
_A = deque()
_A = set()
if not n:
_A = sys.maxsize
elif n < 0:
raise ValueError('''n should be an integer greater than 0.''' )
else:
_A = n
def __A ( self: Union[str, Any] , __A: T ) -> None:
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
_A = self.dq_store.pop()
self.key_reference.remove(__A )
else:
self.dq_store.remove(__A )
self.dq_store.appendleft(__A )
self.key_reference.add(__A )
def __A ( self: Any ) -> None:
for k in self.dq_store:
print(__A )
def __repr__( self: Any ) -> str:
return f"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}"""
if __name__ == "__main__":
import doctest
doctest.testmod()
__A = LRUCache(4)
lru_cache.refer('A')
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer('A')
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| 719 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
_A ,_A = len(_lowercase ), len(grid[0] )
if (
min(_lowercase , _lowercase ) < 0
or row == row_length
or col == col_length
or (row, col) in visit
or grid[row][col] == 1
):
return 0
if row == row_length - 1 and col == col_length - 1:
return 1
visit.add((row, col) )
_A = 0
count += depth_first_search(_lowercase , row + 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , row - 1 , _lowercase , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col + 1 , _lowercase )
count += depth_first_search(_lowercase , _lowercase , col - 1 , _lowercase )
visit.remove((row, col) )
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
if height >= 1:
move_tower(height - 1 , _lowercase , _lowercase , _lowercase )
move_disk(_lowercase , _lowercase )
move_tower(height - 1 , _lowercase , _lowercase , _lowercase )
def __A ( _lowercase , _lowercase ):
'''simple docstring'''
print('''moving disk from''' , _lowercase , '''to''' , _lowercase )
def __A ( ):
'''simple docstring'''
_A = int(input('''Height of hanoi: ''' ).strip() )
move_tower(_lowercase , '''A''' , '''B''' , '''C''' )
if __name__ == "__main__":
main()
| 720 |
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
__A = NewType('DataClass', Any)
__A = NewType('DataClassType', Any)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , _lowercase ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError(
f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" )
def __A ( _lowercase ):
'''simple docstring'''
_A = {str(_lowercase ): choice for choice in choices}
return lambda _lowercase : str_to_choice.get(_lowercase , _lowercase )
def __A ( *,
_lowercase = None , _lowercase = None , _lowercase = dataclasses.MISSING , _lowercase = dataclasses.MISSING , _lowercase = None , **_lowercase , ):
'''simple docstring'''
if metadata is None:
# Important, don't use as default param in function signature because dict is mutable and shared across function calls
_A = {}
if aliases is not None:
_A = aliases
if help is not None:
_A = help
return dataclasses.field(metadata=_lowercase , default=_lowercase , default_factory=_lowercase , **_lowercase )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = 42
def __init__( self: Optional[Any] , __A: Union[DataClassType, Iterable[DataClassType]] , **__A: List[Any] ) -> str:
# To make the default appear when using --help
if "formatter_class" not in kwargs:
_A = ArgumentDefaultsHelpFormatter
super().__init__(**__A )
if dataclasses.is_dataclass(__A ):
_A = [dataclass_types]
_A = list(__A )
for dtype in self.dataclass_types:
self._add_dataclass_arguments(__A )
@staticmethod
def __A ( __A: ArgumentParser , __A: dataclasses.Field ) -> str:
_A = f"""--{field.name}"""
_A = field.metadata.copy()
# field.metadata is not used at all by Data Classes,
# it is provided as a third-party extension mechanism.
if isinstance(field.type , __A ):
raise RuntimeError(
'''Unresolved type detected, which should have been done with the help of '''
'''`typing.get_type_hints` method by default''' )
_A = kwargs.pop('''aliases''' , [] )
if isinstance(__A , __A ):
_A = [aliases]
_A = getattr(field.type , '''__origin__''' , field.type )
if origin_type is Union or (hasattr(__A , '''UnionType''' ) and isinstance(__A , types.UnionType )):
if str not in field.type.__args__ and (
len(field.type.__args__ ) != 2 or type(__A ) not in field.type.__args__
):
raise ValueError(
'''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
''' the argument parser only supports one type per argument.'''
f""" Problem encountered in field '{field.name}'.""" )
if type(__A ) not in field.type.__args__:
# filter `str` in Union
_A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
_A = getattr(field.type , '''__origin__''' , field.type )
elif bool not in field.type.__args__:
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
_A = (
field.type.__args__[0] if isinstance(__A , field.type.__args__[1] ) else field.type.__args__[1]
)
_A = getattr(field.type , '''__origin__''' , field.type )
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
_A = {}
if origin_type is Literal or (isinstance(field.type , __A ) and issubclass(field.type , __A )):
if origin_type is Literal:
_A = field.type.__args__
else:
_A = [x.value for x in field.type]
_A = make_choice_type_function(kwargs['''choices'''] )
if field.default is not dataclasses.MISSING:
_A = field.default
else:
_A = True
elif field.type is bool or field.type == Optional[bool]:
# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
_A = copy(__A )
# Hack because type=bool in argparse does not behave as we want.
_A = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
_A = False if field.default is dataclasses.MISSING else field.default
# This is the value that will get picked if we don't include --field_name in any way
_A = default
# This tells argparse we accept 0 or 1 value after --field_name
_A = '''?'''
# This is the value that will get picked if we do --field_name (without value)
_A = True
elif isclass(__A ) and issubclass(__A , __A ):
_A = field.type.__args__[0]
_A = '''+'''
if field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
elif field.default is dataclasses.MISSING:
_A = True
else:
_A = field.type
if field.default is not dataclasses.MISSING:
_A = field.default
elif field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
else:
_A = True
parser.add_argument(__A , *__A , **__A )
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need those changes/additional keys.
if field.default is True and (field.type is bool or field.type == Optional[bool]):
_A = False
parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__A )
def __A ( self: Dict , __A: DataClassType ) -> List[Any]:
if hasattr(__A , '''_argument_group_name''' ):
_A = self.add_argument_group(dtype._argument_group_name )
else:
_A = self
try:
_A = get_type_hints(__A )
except NameError:
raise RuntimeError(
f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
'''removing line of `from __future__ import annotations` which opts in Postponed '''
'''Evaluation of Annotations (PEP 563)''' )
except TypeError as ex:
# Remove this block when we drop Python 3.9 support
if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__A ):
_A = '''.'''.join(map(__A , sys.version_info[:3] ) )
raise RuntimeError(
f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
'''line of `from __future__ import annotations` which opts in union types as '''
'''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
'''support Python versions that lower than 3.10, you need to use '''
'''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
'''`X | None`.''' ) from ex
raise
for field in dataclasses.fields(__A ):
if not field.init:
continue
_A = type_hints[field.name]
self._parse_dataclass_field(__A , __A )
def __A ( self: int , __A: Any=None , __A: int=False , __A: Any=True , __A: Optional[Any]=None , __A: Any=None , ) -> Tuple[DataClass, ...]:
if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )):
_A = []
if args_filename:
args_files.append(Path(__A ) )
elif look_for_args_file and len(sys.argv ):
args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) )
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
_A = ArgumentParser()
args_file_parser.add_argument(__A , type=__A , action='''append''' )
# Use only remaining args for further parsing (remove the args_file_flag)
_A ,_A = args_file_parser.parse_known_args(args=__A )
_A = vars(__A ).get(args_file_flag.lstrip('''-''' ) , __A )
if cmd_args_file_paths:
args_files.extend([Path(__A ) for p in cmd_args_file_paths] )
_A = []
for args_file in args_files:
if args_file.exists():
file_args += args_file.read_text().split()
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
_A = file_args + args if args is not None else file_args + sys.argv[1:]
_A ,_A = self.parse_known_args(args=__A )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in vars(__A ).items() if k in keys}
for k in keys:
delattr(__A , __A )
_A = dtype(**__A )
outputs.append(__A )
if len(namespace.__dict__ ) > 0:
# additional namespace.
outputs.append(__A )
if return_remaining_strings:
return (*outputs, remaining_args)
else:
if remaining_args:
raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" )
return (*outputs,)
def __A ( self: Tuple , __A: Dict[str, Any] , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = set(args.keys() )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in args.items() if k in keys}
unused_keys.difference_update(inputs.keys() )
_A = dtype(**__A )
outputs.append(__A )
if not allow_extra_keys and unused_keys:
raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__A )}""" )
return tuple(__A )
def __A ( self: Tuple , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
with open(Path(__A ) , encoding='''utf-8''' ) as open_json_file:
_A = json.loads(open_json_file.read() )
_A = self.parse_dict(__A , allow_extra_keys=__A )
return tuple(__A )
def __A ( self: List[Any] , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = self.parse_dict(yaml.safe_load(Path(__A ).read_text() ) , allow_extra_keys=__A )
return tuple(__A )
| 62 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {
'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TimesformerModel',
'TimesformerForVideoClassification',
'TimesformerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timesformer import (
TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TimesformerForVideoClassification,
TimesformerModel,
TimesformerPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 721 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: Optional[int] , __A: Union[str, Any] , __A: int=2 , __A: List[str]=True , __A: List[Any]=False , __A: Union[str, Any]=10 , __A: Optional[int]=3 , __A: List[Any]=32 * 4 , __A: Dict=32 * 6 , __A: Optional[Any]=4 , __A: Any=32 , ) -> str:
_A = parent
_A = batch_size
_A = is_training
_A = use_auxiliary_loss
_A = num_queries
_A = num_channels
_A = min_size
_A = max_size
_A = num_labels
_A = mask_feature_size
def __A ( self: Dict ) -> Optional[int]:
_A = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
__A )
_A = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__A )
_A = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__A ) > 0.5
).float()
_A = (torch.rand((self.batch_size, self.num_labels) , device=__A ) > 0.5).long()
_A = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def __A ( self: Optional[Any] ) -> Tuple:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_28 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def __A ( self: Dict ) -> Tuple:
_A ,_A ,_A ,_A ,_A = self.prepare_config_and_inputs()
_A = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def __A ( self: Optional[int] , __A: Union[str, Any] , __A: Dict ) -> int:
_A = output.encoder_hidden_states
_A = output.pixel_decoder_hidden_states
_A = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(__A ) , config.decoder_config.decoder_layers )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Any , __A: Dict=False ) -> Any:
with torch.no_grad():
_A = MaskFormerModel(config=__A )
model.to(__A )
model.eval()
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A , output_hidden_states=__A )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(__A , __A )
def __A ( self: Optional[Any] , __A: Union[str, Any] , __A: Optional[Any] , __A: Union[str, Any] , __A: Union[str, Any] , __A: List[Any] ) -> int:
_A = MaskFormerForInstanceSegmentation(config=__A )
model.to(__A )
model.eval()
def comm_check_on_output(__A: int ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
_A = model(pixel_values=__A , pixel_mask=__A )
_A = model(__A )
comm_check_on_output(__A )
_A = model(
pixel_values=__A , pixel_mask=__A , mask_labels=__A , class_labels=__A )
comm_check_on_output(__A )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
A_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
A_ = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
A_ = False
A_ = False
A_ = False
A_ = False
def __A ( self: int ) -> Tuple:
_A = MaskFormerModelTester(self )
_A = ConfigTester(self , config_class=__A , has_text_modality=__A )
def __A ( self: List[Any] ) -> Dict:
self.config_tester.run_common_tests()
def __A ( self: Optional[Any] ) -> int:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Dict ) -> Optional[Any]:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__A )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def __A ( self: int ) -> Tuple:
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def __A ( self: List[Any] ) -> Any:
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def __A ( self: Union[str, Any] ) -> Optional[int]:
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def __A ( self: int ) -> List[str]:
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def __A ( self: Union[str, Any] ) -> List[Any]:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __A ( self: List[Any] ) -> Any:
pass
def __A ( self: Dict ) -> Optional[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A )
_A = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_A = [*signature.parameters.keys()]
_A = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __A )
@slow
def __A ( self: int ) -> Optional[Any]:
for model_name in ["facebook/maskformer-swin-small-coco"]:
_A = MaskFormerModel.from_pretrained(__A )
self.assertIsNotNone(__A )
def __A ( self: Optional[Any] ) -> Optional[int]:
_A = (self.model_tester.min_size,) * 2
_A = {
'''pixel_values''': torch.randn((2, 3, *size) , device=__A ),
'''mask_labels''': torch.randn((2, 10, *size) , device=__A ),
'''class_labels''': torch.zeros(2 , 10 , device=__A ).long(),
}
_A = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__A )
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
def __A ( self: Optional[Any] ) -> List[Any]:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(__A , **__A , output_hidden_states=__A )
def __A ( self: Any ) -> Tuple:
_A ,_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_A = model_class(__A ).to(__A )
_A = model(**__A , output_attentions=__A )
self.assertTrue(outputs.attentions is not None )
def __A ( self: Dict ) -> Union[str, Any]:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A ).loss
loss.backward()
def __A ( self: Tuple ) -> Optional[Any]:
# only MaskFormerForInstanceSegmentation has the loss
_A = self.all_model_classes[1]
_A ,_A ,_A ,_A ,_A = self.model_tester.prepare_config_and_inputs()
_A = True
_A = True
_A = model_class(__A )
model.to(__A )
model.train()
_A = model(__A , mask_labels=__A , class_labels=__A )
_A = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
_A = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
_A = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
_A = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=__A )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
__A = 1e-4
def __A ( ):
'''simple docstring'''
_A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self: Union[str, Any] ) -> Optional[int]:
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def __A ( self: List[Any] ) -> Any:
_A = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(__A )
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
_A = torch.tensor(
[[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __A , atol=__A ) )
_A = torch.tensor(
[[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(__A )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Dict ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [
[-1.3_737_124, -1.7_724_937, -1.9_364_233],
[-1.5_977_281, -1.9_867_939, -2.1_523_695],
[-1.5_795_398, -1.9_269_832, -2.093_942],
]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: List[Any] ) -> Dict:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = prepare_img()
_A = image_processor(__A , return_tensors='''pt''' ).to(__A )
_A = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(__A , (1, 3, 8_00, 10_88) )
with torch.no_grad():
_A = model(**__A )
# masks_queries_logits
_A = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
_A = [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
_A = torch.tensor(__A ).to(__A )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __A , atol=__A ) )
# class_queries_logits
_A = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
_A = torch.tensor(
[[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(__A )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __A , atol=__A ) )
def __A ( self: Optional[Any] ) -> str:
_A = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(__A )
.eval()
)
_A = self.default_image_processor
_A = image_processor(
[np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] , segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] , return_tensors='''pt''' , )
_A = inputs['''pixel_values'''].to(__A )
_A = [el.to(__A ) for el in inputs['''mask_labels''']]
_A = [el.to(__A ) for el in inputs['''class_labels''']]
with torch.no_grad():
_A = model(**__A )
self.assertTrue(outputs.loss is not None )
| 62 | 0 |
import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Union[str, Any] , __A: int , __A: int ) -> Optional[int]:
if dst_width < 0 or dst_height < 0:
raise ValueError('''Destination width/height should be > 0''' )
_A = img
_A = img.shape[1]
_A = img.shape[0]
_A = dst_width
_A = dst_height
_A = self.src_w / self.dst_w
_A = self.src_h / self.dst_h
_A = _A = (
np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55
)
def __A ( self: Optional[int] ) -> List[str]:
for i in range(self.dst_h ):
for j in range(self.dst_w ):
_A = self.img[self.get_y(__A )][self.get_x(__A )]
def __A ( self: List[str] , __A: int ) -> int:
return int(self.ratio_x * x )
def __A ( self: Dict , __A: int ) -> int:
return int(self.ratio_y * y )
if __name__ == "__main__":
__A , __A = 800, 600
__A = imread('image_data/lena.jpg', 1)
__A = NearestNeighbour(im, dst_w, dst_h)
n.process()
imshow(
f'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output
)
waitKey(0)
destroyAllWindows()
| 700 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self: int , __A: Optional[int] , __A: Optional[Any] ) -> str:
_A = question_encoder
_A = generator
_A = self.question_encoder
def __A ( self: Optional[int] , __A: Union[str, Any] ) -> Dict:
if os.path.isfile(__A ):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" )
os.makedirs(__A , exist_ok=__A )
_A = os.path.join(__A , '''question_encoder_tokenizer''' )
_A = os.path.join(__A , '''generator_tokenizer''' )
self.question_encoder.save_pretrained(__A )
self.generator.save_pretrained(__A )
@classmethod
def __A ( cls: Optional[Any] , __A: List[str] , **__A: int ) -> Any:
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
_A = kwargs.pop('''config''' , __A )
if config is None:
_A = RagConfig.from_pretrained(__A )
_A = AutoTokenizer.from_pretrained(
__A , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' )
_A = AutoTokenizer.from_pretrained(
__A , config=config.generator , subfolder='''generator_tokenizer''' )
return cls(question_encoder=__A , generator=__A )
def __call__( self: int , *__A: Optional[int] , **__A: List[str] ) -> int:
return self.current_tokenizer(*__A , **__A )
def __A ( self: Dict , *__A: List[str] , **__A: List[str] ) -> Dict:
return self.generator.batch_decode(*__A , **__A )
def __A ( self: Union[str, Any] , *__A: Tuple , **__A: List[str] ) -> Tuple:
return self.generator.decode(*__A , **__A )
def __A ( self: Dict ) -> List[str]:
_A = self.question_encoder
def __A ( self: Union[str, Any] ) -> int:
_A = self.generator
def __A ( self: Dict , __A: List[str] , __A: Optional[List[str]] = None , __A: Optional[int] = None , __A: Optional[int] = None , __A: str = "longest" , __A: str = None , __A: bool = True , **__A: Tuple , ) -> BatchEncoding:
warnings.warn(
'''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
'''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
'''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
'''details''' , __A , )
if max_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
__A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
_A = self.current_tokenizer.model_max_length
_A = self(
text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , )
_A = labels['''input_ids''']
return model_inputs
| 62 | 0 |
import json
from typing import Dict, List, Optional, Tuple, Union
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_led import LEDTokenizer
__A = logging.get_logger(__name__)
__A = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}
__A = {
'vocab_file': {
'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json',
},
'merges_file': {
'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt',
},
'tokenizer_file': {
'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json',
},
}
__A = {
'allenai/led-base-16384': 16384,
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = VOCAB_FILES_NAMES
A_ = PRETRAINED_VOCAB_FILES_MAP
A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A_ = LEDTokenizer
A_ = ["input_ids", "attention_mask"]
def __init__( self: List[str] , __A: List[str]=None , __A: Dict=None , __A: List[Any]=None , __A: List[Any]="replace" , __A: List[Any]="<s>" , __A: Dict="</s>" , __A: Any="</s>" , __A: Optional[int]="<s>" , __A: Dict="<unk>" , __A: Tuple="<pad>" , __A: str="<mask>" , __A: Optional[int]=False , __A: Dict=True , **__A: Union[str, Any] , ) -> List[str]:
super().__init__(
__A , __A , tokenizer_file=__A , errors=__A , bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , unk_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , trim_offsets=__A , **__A , )
_A = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('''add_prefix_space''' , __A ) != add_prefix_space:
_A = getattr(__A , pre_tok_state.pop('''type''' ) )
_A = add_prefix_space
_A = pre_tok_class(**__A )
_A = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
_A = '''post_processor'''
_A = getattr(self.backend_tokenizer , __A , __A )
if tokenizer_component_instance:
_A = json.loads(tokenizer_component_instance.__getstate__() )
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
_A = tuple(state['''sep'''] )
if "cls" in state:
_A = tuple(state['''cls'''] )
_A = False
if state.get('''add_prefix_space''' , __A ) != add_prefix_space:
_A = add_prefix_space
_A = True
if state.get('''trim_offsets''' , __A ) != trim_offsets:
_A = trim_offsets
_A = True
if changes_to_apply:
_A = getattr(__A , state.pop('''type''' ) )
_A = component_class(**__A )
setattr(self.backend_tokenizer , __A , __A )
@property
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
def __A ( self: List[str] ) -> str:
if self._mask_token is None:
if self.verbose:
logger.error('''Using mask_token, but it is not set yet.''' )
return None
return str(self._mask_token )
@mask_token.setter
def __A ( self: List[Any] , __A: Optional[int] ) -> str:
_A = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else value
_A = value
def __A ( self: List[str] , *__A: str , **__A: str ) -> BatchEncoding:
_A = kwargs.get('''is_split_into_words''' , __A )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
'''to use it with pretokenized inputs.''' )
return super()._batch_encode_plus(*__A , **__A )
def __A ( self: List[str] , *__A: int , **__A: int ) -> BatchEncoding:
_A = kwargs.get('''is_split_into_words''' , __A )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
'''to use it with pretokenized inputs.''' )
return super()._encode_plus(*__A , **__A )
def __A ( self: List[str] , __A: str , __A: Optional[str] = None ) -> Tuple[str]:
_A = self._tokenizer.model.save(__A , name=__A )
return tuple(__A )
def __A ( self: Optional[int] , __A: int , __A: Union[str, Any]=None ) -> int:
_A = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def __A ( self: int , __A: List[int] , __A: Optional[List[int]] = None ) -> List[int]:
_A = [self.sep_token_id]
_A = [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: List[str] , __A: Union[Dict[str, EncodedInput], BatchEncoding] , __A: Optional[int] = None , __A: PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __A: Optional[int] = None , __A: Optional[bool] = None , ) -> dict:
_A = super()._pad(
encoded_inputs=__A , max_length=__A , padding_strategy=__A , pad_to_multiple_of=__A , return_attention_mask=__A , )
# Load from model defaults
if return_attention_mask is None:
_A = '''attention_mask''' in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
_A = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
_A = len(encoded_inputs['''global_attention_mask'''] ) != len(__A )
if needs_to_be_padded:
_A = len(__A ) - len(encoded_inputs['''global_attention_mask'''] )
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
_A = (
encoded_inputs['''global_attention_mask'''] + [-1] * difference
)
elif self.padding_side == "left":
_A = [-1] * difference + encoded_inputs[
'''global_attention_mask'''
]
else:
raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) )
return encoded_inputs
| 701 |
from __future__ import annotations
def __A ( _lowercase , _lowercase , _lowercase , _lowercase ): # noqa: E741
'''simple docstring'''
while r - l > 1:
_A = (l + r) // 2
if v[m] >= key:
_A = m
else:
_A = m # noqa: E741
return r
def __A ( _lowercase ):
'''simple docstring'''
if len(_lowercase ) == 0:
return 0
_A = [0] * len(_lowercase )
_A = 1
_A = v[0]
for i in range(1 , len(_lowercase ) ):
if v[i] < tail[0]:
_A = v[i]
elif v[i] > tail[length - 1]:
_A = v[i]
length += 1
else:
_A = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 62 | 0 |
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))
| 702 |
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
__A = logging.getLogger(__name__)
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "sequence-classification"
def __init__( self: str , __A: Union[str, Any] ) -> List[str]:
if type(__A ) == dict:
_A = Namespace(**__A )
_A = glue_output_modes[hparams.task]
_A = glue_tasks_num_labels[hparams.task]
super().__init__(__A , __A , self.mode )
def __A ( self: Optional[Any] , **__A: Union[str, Any] ) -> Optional[int]:
return self.model(**__A )
def __A ( self: Any , __A: Union[str, Any] , __A: int ) -> Optional[Any]:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A = outputs[0]
_A = self.trainer.lr_schedulers[0]['''scheduler''']
_A = {'''loss''': loss, '''rate''': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def __A ( self: List[str] ) -> Dict:
_A = self.hparams
_A = processors[args.task]()
_A = processor.get_labels()
for mode in ["train", "dev"]:
_A = self._feature_file(__A )
if os.path.exists(__A ) and not args.overwrite_cache:
logger.info('''Loading features from cached file %s''' , __A )
else:
logger.info('''Creating features from dataset file at %s''' , args.data_dir )
_A = (
processor.get_dev_examples(args.data_dir )
if mode == '''dev'''
else processor.get_train_examples(args.data_dir )
)
_A = convert_examples_to_features(
__A , 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''' , __A )
torch.save(__A , __A )
def __A ( self: List[str] , __A: str , __A: int , __A: bool = False ) -> DataLoader:
_A = '''dev''' if mode == '''test''' else mode
_A = self._feature_file(__A )
logger.info('''Loading features from cached file %s''' , __A )
_A = torch.load(__A )
_A = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
_A = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
_A = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
_A = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
_A = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , )
def __A ( self: List[str] , __A: str , __A: Tuple ) -> str:
_A = {'''input_ids''': batch[0], '''attention_mask''': batch[1], '''labels''': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
_A = batch[2] if self.config.model_type in ['''bert''', '''xlnet''', '''albert'''] else None
_A = self(**__A )
_A ,_A = outputs[:2]
_A = logits.detach().cpu().numpy()
_A = inputs['''labels'''].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __A ( self: str , __A: Dict ) -> tuple:
_A = torch.stack([x['''val_loss'''] for x in outputs] ).mean().detach().cpu().item()
_A = np.concatenate([x['''pred'''] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
_A = np.argmax(__A , axis=1 )
elif self.hparams.glue_output_mode == "regression":
_A = np.squeeze(__A )
_A = np.concatenate([x['''target'''] for x in outputs] , axis=0 )
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = [[] for _ in range(out_label_ids.shape[0] )]
_A = {**{'''val_loss''': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )}
_A = dict(results.items() )
_A = results
return ret, preds_list, out_label_list
def __A ( self: Any , __A: list ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = ret['''log''']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __A ( self: int , __A: Union[str, Any] ) -> dict:
_A ,_A ,_A = self._eval_end(__A )
_A = 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 ( __A: Optional[Any] , __A: Optional[Any] ) -> Optional[Any]:
BaseTransformer.add_model_specific_args(__A , __A )
parser.add_argument(
'''--max_seq_length''' , default=1_28 , type=__A , 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=__A , required=__A , help='''The GLUE task to run''' , )
parser.add_argument(
'''--gpus''' , default=0 , type=__A , 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 __A ( ):
'''simple docstring'''
_A = argparse.ArgumentParser()
add_generic_args(_lowercase , os.getcwd() )
_A = GLUETransformer.add_model_specific_args(_lowercase , os.getcwd() )
_A = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
_A = os.path.join(
'''./results''' , f"""{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}""" , )
os.makedirs(args.output_dir )
_A = GLUETransformer(_lowercase )
_A = generic_train(_lowercase , _lowercase )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
_A = sorted(glob.glob(os.path.join(args.output_dir , '''checkpoint-epoch=*.ckpt''' ) , recursive=_lowercase ) )
_A = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(_lowercase )
if __name__ == "__main__":
main()
| 62 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.