code
stringlengths 82
53.2k
| code_codestyle
int64 0
721
| style_context
stringlengths 91
41.9k
| style_context_codestyle
int64 0
699
| label
int64 0
1
|
---|---|---|---|---|
"""simple docstring"""
import inspect
from typing import List, Optional, Tuple, Union
import numpy as np
import PIL
import torch
import torch.utils.checkpoint
from ...models import UNetaDModel, VQModel
from ...schedulers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> int:
'''simple docstring'''
lowercase_ = image.size
lowercase_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
lowercase_ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] )
lowercase_ = np.array(SCREAMING_SNAKE_CASE_ ).astype(np.floataa ) / 255.0
lowercase_ = image[None].transpose(0 , 3 , 1 , 2 )
lowercase_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ )
return 2.0 * image - 1.0
class SCREAMING_SNAKE_CASE__ ( snake_case_ ):
def __init__( self : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Union[str, Any] , ):
"""simple docstring"""
super().__init__()
self.register_modules(vqvae=lowerCAmelCase_ , unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_)
@torch.no_grad()
def __call__( self : List[Any] , lowerCAmelCase_ : Union[str, Any] = None , lowerCAmelCase_ : Optional[int] = 1 , lowerCAmelCase_ : int = 1_0_0 , lowerCAmelCase_ : List[str] = 0.0 , lowerCAmelCase_ : List[Any] = None , lowerCAmelCase_ : List[str] = "pil" , lowerCAmelCase_ : Dict = True , ):
"""simple docstring"""
if isinstance(lowerCAmelCase_ , PIL.Image.Image):
lowercase_ = 1
elif isinstance(lowerCAmelCase_ , torch.Tensor):
lowercase_ = image.shape[0]
else:
raise ValueError(F'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCAmelCase_)}''')
if isinstance(lowerCAmelCase_ , PIL.Image.Image):
lowercase_ = preprocess(lowerCAmelCase_)
lowercase_ = image.shape[-2:]
# in_channels should be 6: 3 for latents, 3 for low resolution image
lowercase_ = (batch_size, self.unet.config.in_channels // 2, height, width)
lowercase_ = next(self.unet.parameters()).dtype
lowercase_ = randn_tensor(lowerCAmelCase_ , generator=lowerCAmelCase_ , device=self.device , dtype=lowerCAmelCase_)
lowercase_ = image.to(device=self.device , dtype=lowerCAmelCase_)
# set timesteps and move to the correct device
self.scheduler.set_timesteps(lowerCAmelCase_ , device=self.device)
lowercase_ = self.scheduler.timesteps
# scale the initial noise by the standard deviation required by the scheduler
lowercase_ = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
lowercase_ = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
lowercase_ = {}
if accepts_eta:
lowercase_ = eta
for t in self.progress_bar(lowerCAmelCase_):
# concat latents and low resolution image in the channel dimension.
lowercase_ = torch.cat([latents, image] , dim=1)
lowercase_ = self.scheduler.scale_model_input(lowerCAmelCase_ , lowerCAmelCase_)
# predict the noise residual
lowercase_ = self.unet(lowerCAmelCase_ , lowerCAmelCase_).sample
# compute the previous noisy sample x_t -> x_t-1
lowercase_ = self.scheduler.step(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_).prev_sample
# decode the image latents with the VQVAE
lowercase_ = self.vqvae.decode(lowerCAmelCase_).sample
lowercase_ = torch.clamp(lowerCAmelCase_ , -1.0 , 1.0)
lowercase_ = image / 2 + 0.5
lowercase_ = image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowercase_ = self.numpy_to_pil(lowerCAmelCase_)
if not return_dict:
return (image,)
return ImagePipelineOutput(images=lowerCAmelCase_)
| 567 |
import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch
import numpy as np
import pytest
from absl.testing import parameterized
import datasets
from datasets import load_metric
from .utils import for_all_test_methods, local, slow
# mark all tests as integration
__a : Optional[int] = pytest.mark.integration
__a : List[str] = {'''comet'''}
__a : Union[str, Any] = importlib.util.find_spec('''fairseq''') is not None
__a : Tuple = {'''code_eval'''}
__a : Any = os.name == '''nt'''
__a : Dict = {'''bertscore''', '''frugalscore''', '''perplexity'''}
__a : Optional[int] = importlib.util.find_spec('''transformers''') is not None
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> List[str]:
@wraps(SCREAMING_SNAKE_CASE_ )
def wrapper(self ,SCREAMING_SNAKE_CASE_ ):
if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
self.skipTest("\"test requires Fairseq\"" )
else:
test_case(self ,SCREAMING_SNAKE_CASE_ )
return wrapper
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> int:
@wraps(SCREAMING_SNAKE_CASE_ )
def wrapper(self ,SCREAMING_SNAKE_CASE_ ):
if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
self.skipTest("\"test requires transformers\"" )
else:
test_case(self ,SCREAMING_SNAKE_CASE_ )
return wrapper
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> List[Any]:
@wraps(SCREAMING_SNAKE_CASE_ )
def wrapper(self ,SCREAMING_SNAKE_CASE_ ):
if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
self.skipTest("\"test not supported on Windows\"" )
else:
test_case(self ,SCREAMING_SNAKE_CASE_ )
return wrapper
def snake_case_ ( ) -> str:
lowercase__ : Optional[int] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )]
return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names() )
@for_all_test_methods(
snake_case_ , snake_case_ , snake_case_ )
@local
class UpperCAmelCase( parameterized.TestCase ):
"""simple docstring"""
a : List[str] = {}
a : List[Any] = None
@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" )
@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" )
def __a ( self , lowerCamelCase ) -> Any:
"""simple docstring"""
lowercase__ : int = "[...]"
lowercase__ : Any = importlib.import_module(
datasets.load.metric_module_factory(os.path.join("metrics" , lowerCamelCase ) ).module_path )
lowercase__ : List[Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=lowerCamelCase )
# check parameters
lowercase__ : int = inspect.signature(metric._compute ).parameters
self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs
# run doctest
with self.patch_intensive_calls(lowerCamelCase , metric_module.__name__ ):
with self.use_local_metrics():
try:
lowercase__ : str = doctest.testmod(lowerCamelCase , verbose=lowerCamelCase , raise_on_error=lowerCamelCase )
except doctest.UnexpectedException as e:
raise e.exc_info[1] # raise the exception that doctest caught
self.assertEqual(results.failed , 0 )
self.assertGreater(results.attempted , 1 )
@slow
def __a ( self , lowerCamelCase ) -> Optional[Any]:
"""simple docstring"""
lowercase__ : Optional[Any] = "[...]"
lowercase__ : List[Any] = importlib.import_module(
datasets.load.metric_module_factory(os.path.join("metrics" , lowerCamelCase ) ).module_path )
# run doctest
with self.use_local_metrics():
lowercase__ : List[str] = doctest.testmod(lowerCamelCase , verbose=lowerCamelCase , raise_on_error=lowerCamelCase )
self.assertEqual(results.failed , 0 )
self.assertGreater(results.attempted , 1 )
@contextmanager
def __a ( self , lowerCamelCase , lowerCamelCase ) -> str:
"""simple docstring"""
if metric_name in self.INTENSIVE_CALLS_PATCHER:
with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCamelCase ):
yield
else:
yield
@contextmanager
def __a ( self ) -> int:
"""simple docstring"""
def load_local_metric(lowerCamelCase , *lowerCamelCase , **lowerCamelCase ):
return load_metric(os.path.join("metrics" , lowerCamelCase ) , *lowerCamelCase , **lowerCamelCase )
with patch("datasets.load_metric" ) as mock_load_metric:
lowercase__ : Any = load_local_metric
yield
@classmethod
def __a ( cls , lowerCamelCase ) -> Optional[int]:
"""simple docstring"""
def wrapper(lowerCamelCase ):
lowercase__ : Dict = contextmanager(lowerCamelCase )
lowercase__ : Tuple = patcher
return patcher
return wrapper
@LocalMetricTest.register_intensive_calls_patcher("bleurt" )
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
import tensorflow.compat.va as tf
from bleurt.score import Predictor
tf.flags.DEFINE_string("sv" ,"" ,"" ) # handle pytest cli flags
class UpperCAmelCase( snake_case_ ):
"""simple docstring"""
def __a ( self , lowerCamelCase ) -> Optional[Any]:
"""simple docstring"""
assert len(input_dict["input_ids"] ) == 2
return np.array([1.03, 1.04] )
# mock predict_fn which is supposed to do a forward pass with a bleurt model
with patch("bleurt.score._create_predictor" ) as mock_create_predictor:
lowercase__ : Tuple = MockedPredictor()
yield
@LocalMetricTest.register_intensive_calls_patcher("bertscore" )
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Optional[int]:
import torch
def bert_cos_score_idf(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ):
return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_SNAKE_CASE_ ) )
# mock get_model which is supposed to do download a bert model
# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
with patch("bert_score.scorer.get_model" ), patch(
"bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf:
lowercase__ : Tuple = bert_cos_score_idf
yield
@LocalMetricTest.register_intensive_calls_patcher("comet" )
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Any:
def load_from_checkpoint(SCREAMING_SNAKE_CASE_ ):
class UpperCAmelCase:
"""simple docstring"""
def __a ( self , lowerCamelCase , *lowerCamelCase , **lowerCamelCase ) -> Dict:
"""simple docstring"""
assert len(lowerCamelCase ) == 2
lowercase__ : List[Any] = [0.19, 0.92]
return scores, sum(lowerCamelCase ) / len(lowerCamelCase )
return Model()
# mock load_from_checkpoint which is supposed to do download a bert model
# mock load_from_checkpoint which is supposed to do download a bert model
with patch("comet.download_model" ) as mock_download_model:
lowercase__ : int = None
with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint:
lowercase__ : Optional[int] = load_from_checkpoint
yield
def snake_case_ ( ) -> Tuple:
lowercase__ : Dict = load_metric(os.path.join("metrics" ,"seqeval" ) )
lowercase__ : str = "ERROR"
lowercase__ : Union[str, Any] = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
with pytest.raises(SCREAMING_SNAKE_CASE_ ,match=re.escape(SCREAMING_SNAKE_CASE_ ) ):
metric.compute(predictions=[] ,references=[] ,scheme=SCREAMING_SNAKE_CASE_ ) | 397 | 0 |
'''simple docstring'''
import gc
import unittest
import numpy as np
import torch
from torch.backends.cuda import sdp_kernel
from diffusers import (
CMStochasticIterativeScheduler,
ConsistencyModelPipeline,
UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class a__ ( UpperCAmelCase_ , unittest.TestCase ):
"""simple docstring"""
__UpperCamelCase : Union[str, Any] = ConsistencyModelPipeline
__UpperCamelCase : List[str] = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
__UpperCamelCase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
# Override required_optional_params to remove num_images_per_prompt
__UpperCamelCase : Dict = frozenset(
[
'num_inference_steps',
'generator',
'latents',
'output_type',
'return_dict',
'callback',
'callback_steps',
] )
@property
def _snake_case (self ):
__lowerCAmelCase = UNetaDModel.from_pretrained(
'''diffusers/consistency-models-test''' , subfolder='''test_unet''' , )
return unet
@property
def _snake_case (self ):
__lowerCAmelCase = UNetaDModel.from_pretrained(
'''diffusers/consistency-models-test''' , subfolder='''test_unet_class_cond''' , )
return unet
def _snake_case (self , __lowercase=False ):
if class_cond:
__lowerCAmelCase = self.dummy_cond_unet
else:
__lowerCAmelCase = self.dummy_uncond_unet
# Default to CM multistep sampler
__lowerCAmelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=80.0 , )
__lowerCAmelCase = {
'''unet''': unet,
'''scheduler''': scheduler,
}
return components
def _snake_case (self , __lowercase , __lowercase=0 ):
if str(_lowercase ).startswith('''mps''' ):
__lowerCAmelCase = torch.manual_seed(_lowercase )
else:
__lowerCAmelCase = torch.Generator(device=_lowercase ).manual_seed(_lowercase )
__lowerCAmelCase = {
'''batch_size''': 1,
'''num_inference_steps''': None,
'''timesteps''': [22, 0],
'''generator''': generator,
'''output_type''': '''np''',
}
return inputs
def _snake_case (self ):
__lowerCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__lowerCAmelCase = self.get_dummy_components()
__lowerCAmelCase = ConsistencyModelPipeline(**_lowercase )
__lowerCAmelCase = pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_dummy_inputs(_lowercase )
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 32, 32, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def _snake_case (self ):
__lowerCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__lowerCAmelCase = self.get_dummy_components(class_cond=_lowercase )
__lowerCAmelCase = ConsistencyModelPipeline(**_lowercase )
__lowerCAmelCase = pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_dummy_inputs(_lowercase )
__lowerCAmelCase = 0
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 32, 32, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def _snake_case (self ):
__lowerCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__lowerCAmelCase = self.get_dummy_components()
__lowerCAmelCase = ConsistencyModelPipeline(**_lowercase )
__lowerCAmelCase = pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_dummy_inputs(_lowercase )
__lowerCAmelCase = 1
__lowerCAmelCase = None
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 32, 32, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def _snake_case (self ):
__lowerCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__lowerCAmelCase = self.get_dummy_components(class_cond=_lowercase )
__lowerCAmelCase = ConsistencyModelPipeline(**_lowercase )
__lowerCAmelCase = pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_dummy_inputs(_lowercase )
__lowerCAmelCase = 1
__lowerCAmelCase = None
__lowerCAmelCase = 0
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 32, 32, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
@slow
@require_torch_gpu
class a__ ( unittest.TestCase ):
"""simple docstring"""
def _snake_case (self ):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _snake_case (self , __lowercase=0 , __lowercase=False , __lowercase="cpu" , __lowercase=torch.floataa , __lowercase=(1, 3, 64, 64) ):
__lowerCAmelCase = torch.manual_seed(_lowercase )
__lowerCAmelCase = {
'''num_inference_steps''': None,
'''timesteps''': [22, 0],
'''class_labels''': 0,
'''generator''': generator,
'''output_type''': '''np''',
}
if get_fixed_latents:
__lowerCAmelCase = self.get_fixed_latents(seed=_lowercase , device=_lowercase , dtype=_lowercase , shape=_lowercase )
__lowerCAmelCase = latents
return inputs
def _snake_case (self , __lowercase=0 , __lowercase="cpu" , __lowercase=torch.floataa , __lowercase=(1, 3, 64, 64) ):
if type(_lowercase ) == str:
__lowerCAmelCase = torch.device(_lowercase )
__lowerCAmelCase = torch.Generator(device=_lowercase ).manual_seed(_lowercase )
__lowerCAmelCase = randn_tensor(_lowercase , generator=_lowercase , device=_lowercase , dtype=_lowercase )
return latents
def _snake_case (self ):
__lowerCAmelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__lowerCAmelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=80.0 , )
__lowerCAmelCase = ConsistencyModelPipeline(unet=_lowercase , scheduler=_lowercase )
pipe.to(torch_device=_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_inputs()
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 64, 64, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
def _snake_case (self ):
__lowerCAmelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__lowerCAmelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=80.0 , )
__lowerCAmelCase = ConsistencyModelPipeline(unet=_lowercase , scheduler=_lowercase )
pipe.to(torch_device=_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_inputs()
__lowerCAmelCase = 1
__lowerCAmelCase = None
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 64, 64, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
@require_torch_a
def _snake_case (self ):
__lowerCAmelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__lowerCAmelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=80.0 , )
__lowerCAmelCase = ConsistencyModelPipeline(unet=_lowercase , scheduler=_lowercase )
pipe.to(torch_device=_lowercase , torch_dtype=torch.floataa )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_inputs(get_fixed_latents=_lowercase , device=_lowercase )
# Ensure usage of flash attention in torch 2.0
with sdp_kernel(enable_flash=_lowercase , enable_math=_lowercase , enable_mem_efficient=_lowercase ):
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 64, 64, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
@require_torch_a
def _snake_case (self ):
__lowerCAmelCase = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__lowerCAmelCase = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=80.0 , )
__lowerCAmelCase = ConsistencyModelPipeline(unet=_lowercase , scheduler=_lowercase )
pipe.to(torch_device=_lowercase , torch_dtype=torch.floataa )
pipe.set_progress_bar_config(disable=_lowercase )
__lowerCAmelCase = self.get_inputs(get_fixed_latents=_lowercase , device=_lowercase )
__lowerCAmelCase = 1
__lowerCAmelCase = None
# Ensure usage of flash attention in torch 2.0
with sdp_kernel(enable_flash=_lowercase , enable_math=_lowercase , enable_mem_efficient=_lowercase ):
__lowerCAmelCase = pipe(**_lowercase ).images
assert image.shape == (1, 64, 64, 3)
__lowerCAmelCase = image[0, -3:, -3:, -1]
__lowerCAmelCase = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
| 703 |
'''simple docstring'''
from manim import *
class a__ ( __A ):
"""simple docstring"""
def _snake_case (self ):
__lowerCAmelCase = Rectangle(height=0.5 , width=0.5 )
__lowerCAmelCase = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 )
__lowerCAmelCase = [mem.copy() for i in range(6 )]
__lowerCAmelCase = [mem.copy() for i in range(6 )]
__lowerCAmelCase = VGroup(*__lowercase ).arrange(__lowercase , buff=0 )
__lowerCAmelCase = VGroup(*__lowercase ).arrange(__lowercase , buff=0 )
__lowerCAmelCase = VGroup(__lowercase , __lowercase ).arrange(__lowercase , buff=0 )
__lowerCAmelCase = Text('''CPU''' , font_size=24 )
__lowerCAmelCase = Group(__lowercase , __lowercase ).arrange(__lowercase , buff=0.5 , aligned_edge=__lowercase )
cpu.move_to([-2.5, -0.5, 0] )
self.add(__lowercase )
__lowerCAmelCase = [mem.copy() for i in range(1 )]
__lowerCAmelCase = VGroup(*__lowercase ).arrange(__lowercase , buff=0 )
__lowerCAmelCase = Text('''GPU''' , font_size=24 )
__lowerCAmelCase = Group(__lowercase , __lowercase ).arrange(__lowercase , buff=0.5 , aligned_edge=__lowercase )
gpu.align_to(__lowercase , __lowercase )
gpu.set_x(gpu.get_x() - 1 )
self.add(__lowercase )
__lowerCAmelCase = [mem.copy() for i in range(6 )]
__lowerCAmelCase = VGroup(*__lowercase ).arrange(__lowercase , buff=0 )
__lowerCAmelCase = Text('''Model''' , font_size=24 )
__lowerCAmelCase = Group(__lowercase , __lowercase ).arrange(__lowercase , buff=0.5 , aligned_edge=__lowercase )
model.move_to([3, -1.0, 0] )
self.play(
Create(__lowercase , run_time=1 ) , Create(__lowercase , run_time=1 ) , Create(__lowercase , run_time=1 ) , )
__lowerCAmelCase = MarkupText(
F"""First, an empty model skeleton is loaded\ninto <span fgcolor='{YELLOW}'>memory</span> without using much RAM.""" , font_size=24 , )
__lowerCAmelCase = Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
__lowerCAmelCase = MarkupText(
F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , )
key_text.move_to([-5, 2.4, 0] )
step_a.move_to([2, 2, 0] )
self.play(Write(__lowercase , run_time=2.5 ) , Write(__lowercase ) , Write(__lowercase ) )
self.add(__lowercase )
__lowerCAmelCase = []
__lowerCAmelCase = []
__lowerCAmelCase = []
for i, rect in enumerate(__lowercase ):
__lowerCAmelCase = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(__lowercase , opacity=0.7 )
cpu_target.move_to(__lowercase )
cpu_target.generate_target()
__lowerCAmelCase = 0.4_6 / 4
__lowerCAmelCase = 0.4_6 / 3
if i == 0:
cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=__lowercase )
cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 )
elif i == 3:
cpu_target.target.next_to(cpu_targs[0].target , direction=__lowercase , buff=0.0 )
else:
cpu_target.target.next_to(cpu_targs[i - 1].target , direction=__lowercase , buff=0.0 )
cpu_targs.append(__lowercase )
first_animations.append(rect.animate(run_time=0.5 ).set_stroke(__lowercase ) )
second_animations.append(MoveToTarget(__lowercase , run_time=1.5 ) )
self.play(*__lowercase )
self.play(*__lowercase )
self.wait()
| 474 | 0 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class lowerCAmelCase__ ( unittest.TestCase ):
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in ["bert-base-uncased"]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModel.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModel.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in ["bert-base-uncased"]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelForPreTraining.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelForPreTraining.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelForCausalLM.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
A__ , A__ = TFAutoModelForCausalLM.from_pretrained(
UpperCamelCase__ , output_loading_info=UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelForCausalLM.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
A__ , A__ = AutoModelForCausalLM.from_pretrained(
UpperCamelCase__ , output_loading_info=UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelWithLMHead.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelWithLMHead.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelForMaskedLM.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
A__ , A__ = TFAutoModelForMaskedLM.from_pretrained(
UpperCamelCase__ , output_loading_info=UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelForMaskedLM.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
A__ , A__ = AutoModelForMaskedLM.from_pretrained(
UpperCamelCase__ , output_loading_info=UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
A__ , A__ = TFAutoModelForSeqaSeqLM.from_pretrained(
UpperCamelCase__ , output_loading_info=UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
A__ , A__ = AutoModelForSeqaSeqLM.from_pretrained(
UpperCamelCase__ , output_loading_info=UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in ["bert-base-uncased"]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelForSequenceClassification.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelForSequenceClassification.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
@slow
def lowercase_ ( self ):
'''simple docstring'''
for model_name in ["bert-base-uncased"]:
A__ = AutoConfig.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = TFAutoModelForQuestionAnswering.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
A__ = AutoModelForQuestionAnswering.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
def lowercase_ ( self ):
'''simple docstring'''
A__ = TFAutoModelWithLMHead.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(model.num_parameters() , 1_44_10 )
self.assertEqual(model.num_parameters(only_trainable=UpperCamelCase__ ) , 1_44_10 )
A__ = AutoModelWithLMHead.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(model.num_parameters() , 1_44_10 )
self.assertEqual(model.num_parameters(only_trainable=UpperCamelCase__ ) , 1_44_10 )
def lowercase_ ( self ):
'''simple docstring'''
A__ = TFAutoModelWithLMHead.from_pretrained(UpperCamelCase__ , from_pt=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(model.num_parameters() , 1_44_10 )
self.assertEqual(model.num_parameters(only_trainable=UpperCamelCase__ ) , 1_44_10 )
A__ = AutoModelWithLMHead.from_pretrained(UpperCamelCase__ , from_tf=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(model.num_parameters() , 1_44_10 )
self.assertEqual(model.num_parameters(only_trainable=UpperCamelCase__ ) , 1_44_10 ) | 337 |
"""simple docstring"""
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
__UpperCAmelCase =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 lowerCAmelCase__ ( UpperCAmelCase_ ):
def __init__( self , *UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ ):
'''simple docstring'''
super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
A__ = eval_examples
A__ = post_process_function
A__ = quant_trainer_args
A__ = 1_28 # default number of calibration samples
def lowercase_ ( self , UpperCamelCase__=None ):
'''simple docstring'''
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(UpperCamelCase__ , description="Calibration" )
return DataLoader(
UpperCamelCase__ , 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=UpperCamelCase__ , )
def lowercase_ ( self , UpperCamelCase__=None ):
'''simple docstring'''
A__ = self.train_dataset if calib_dataset is None else calib_dataset
A__ = self.get_calib_dataloader(UpperCamelCase__ )
A__ = self.model
quant_trainer.configure_model(UpperCamelCase__ , self.quant_trainer_args , calib=UpperCamelCase__ )
model.eval()
quant_trainer.enable_calibration(UpperCamelCase__ )
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(UpperCamelCase__ ):
# Prediction step
A__ , A__ , A__ = self.prediction_step(UpperCamelCase__ , UpperCamelCase__ , prediction_loss_only=UpperCamelCase__ )
if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
break
quant_trainer.finish_calibration(UpperCamelCase__ , self.quant_trainer_args )
A__ = model
def lowercase_ ( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__ = "eval" ):
'''simple docstring'''
A__ = self.eval_dataset if eval_dataset is None else eval_dataset
A__ = self.get_eval_dataloader(UpperCamelCase__ )
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(
UpperCamelCase__ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , )
finally:
A__ = compute_metrics
if self.post_process_function is not None and self.compute_metrics is not None:
A__ = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , output.predictions )
A__ = self.compute_metrics(UpperCamelCase__ )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
A__ = metrics.pop(UpperCamelCase__ )
self.log(UpperCamelCase__ )
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 , UpperCamelCase__ )
return metrics
def lowercase_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__ = "test" ):
'''simple docstring'''
A__ = self.get_test_dataloader(UpperCamelCase__ )
# 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(
UpperCamelCase__ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , )
finally:
A__ = compute_metrics
if self.post_process_function is None or self.compute_metrics is None:
return output
A__ = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , output.predictions , "predict" )
A__ = self.compute_metrics(UpperCamelCase__ )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
A__ = metrics.pop(UpperCamelCase__ )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCamelCase__ )
def lowercase_ ( self , UpperCamelCase__="./" ):
'''simple docstring'''
A__ = self.eval_dataset
A__ = self.get_eval_dataloader(UpperCamelCase__ )
A__ = next(iter(UpperCamelCase__ ) )
# saving device - to make it consistent
A__ = torch.device("cuda" if torch.cuda.is_available() else "cpu" )
# convert to tuple
A__ = tuple(v.to(UpperCamelCase__ ) 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(UpperCamelCase__ )
model.eval()
model.float()
A__ = model.module if hasattr(UpperCamelCase__ , "module" ) else model
quant_trainer.configure_model(UpperCamelCase__ , self.quant_trainer_args )
A__ = os.path.join(UpperCamelCase__ , "model.onnx" )
logger.info(f"""exporting model to {output_model_file}""" )
A__ = {0: "batch_size", 1: "seq_len"}
torch.onnx.export(
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , export_params=UpperCamelCase__ , opset_version=13 , do_constant_folding=UpperCamelCase__ , 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=UpperCamelCase__ , )
logger.info("onnx export finished" ) | 337 | 1 |
'''simple docstring'''
import logging
import numpy as np
import pytest
from scipy.linalg import eigh
logging.basicConfig(level=logging.INFO, format='''%(message)s''')
def __magic_name__( _A ):
'''simple docstring'''
return input_array.reshape((input_array.size, 1) )
def __magic_name__( _A , _A , _A ):
'''simple docstring'''
UpperCamelCase__ = np.nan
for i in range(_A ):
UpperCamelCase__ = features[:, labels == i]
UpperCamelCase__ = data.mean(1 )
# Centralize the data of class i
UpperCamelCase__ = data - column_reshape(_A )
if i > 0:
# If covariance_sum is not None
covariance_sum += np.dot(_A , centered_data.T )
else:
# If covariance_sum is np.nan (i.e. first loop)
UpperCamelCase__ = np.dot(_A , centered_data.T )
return covariance_sum / features.shape[1]
def __magic_name__( _A , _A , _A ):
'''simple docstring'''
UpperCamelCase__ = features.mean(1 )
UpperCamelCase__ = np.nan
for i in range(_A ):
UpperCamelCase__ = features[:, labels == i]
UpperCamelCase__ = data.shape[1]
UpperCamelCase__ = data.mean(1 )
if i > 0:
# If covariance_sum is not None
covariance_sum += device_data * np.dot(
column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , )
else:
# If covariance_sum is np.nan (i.e. first loop)
UpperCamelCase__ = device_data * np.dot(
column_reshape(_A ) - column_reshape(_A ) , (column_reshape(_A ) - column_reshape(_A )).T , )
return covariance_sum / features.shape[1]
def __magic_name__( _A , _A ):
'''simple docstring'''
if features.any():
UpperCamelCase__ = features.mean(1 )
# Center the dataset
UpperCamelCase__ = features - np.reshape(_A , (data_mean.size, 1) )
UpperCamelCase__ = np.dot(_A , centered_data.T ) / features.shape[1]
UpperCamelCase__ , UpperCamelCase__ = np.linalg.eigh(_A )
# Take all the columns in the reverse order (-1), and then takes only the first
UpperCamelCase__ = eigenvectors[:, ::-1][:, 0:dimensions]
# Project the database on the new space
UpperCamelCase__ = np.dot(filtered_eigenvectors.T , _A )
logging.info("""Principal Component Analysis computed""" )
return projected_data
else:
logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A )
logging.error("""Dataset empty""" )
raise AssertionError
def __magic_name__( _A , _A , _A , _A ):
'''simple docstring'''
assert classes > dimensions
# Check if features have been already loaded
if features.any:
UpperCamelCase__ , UpperCamelCase__ = eigh(
covariance_between_classes(_A , _A , _A ) , covariance_within_classes(_A , _A , _A ) , )
UpperCamelCase__ = eigenvectors[:, ::-1][:, :dimensions]
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = np.linalg.svd(_A )
UpperCamelCase__ = svd_matrix[:, 0:dimensions]
UpperCamelCase__ = np.dot(filtered_svd_matrix.T , _A )
logging.info("""Linear Discriminant Analysis computed""" )
return projected_data
else:
logging.basicConfig(level=logging.ERROR , format="""%(message)s""" , force=_A )
logging.error("""Dataset empty""" )
raise AssertionError
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] )
UpperCamelCase__ = np.array([0, 0, 0, 1, 1] )
UpperCamelCase__ = 2
UpperCamelCase__ = 2
# Assert that the function raises an AssertionError if dimensions > classes
with pytest.raises(_A ) as error_info:
UpperCamelCase__ = linear_discriminant_analysis(
_A , _A , _A , _A )
if isinstance(_A , np.ndarray ):
raise AssertionError(
"""Did not raise AssertionError for dimensions > classes""" )
assert error_info.type is AssertionError
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] )
UpperCamelCase__ = 2
UpperCamelCase__ = np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] )
with pytest.raises(_A ) as error_info:
UpperCamelCase__ = principal_component_analysis(_A , _A )
if not np.allclose(_A , _A ):
raise AssertionError
assert error_info.type is AssertionError
if __name__ == "__main__":
import doctest
doctest.testmod()
| 265 |
'''simple docstring'''
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation
import warnings
from .state import AcceleratorState, GradientState
warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''')
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : Optional[int] , lowercase : Optional[int] , lowercase : Optional[Any] , lowercase : bool = True , lowercase : bool = False ) -> Optional[int]:
'''simple docstring'''
UpperCamelCase__ = scheduler
UpperCamelCase__ = optimizers if isinstance(lowercase , (list, tuple) ) else [optimizers]
UpperCamelCase__ = split_batches
UpperCamelCase__ = step_with_optimizer
UpperCamelCase__ = GradientState()
def A ( self : int , *lowercase : int , **lowercase : str ) -> str:
'''simple docstring'''
if not self.step_with_optimizer:
# No link between scheduler and optimizer -> just step
self.scheduler.step(*lowercase , **lowercase )
return
# Otherwise, first make sure the optimizer was stepped.
if not self.gradient_state.sync_gradients:
if self.gradient_state.adjust_scheduler:
self.scheduler._step_count += 1
return
for opt in self.optimizers:
if opt.step_was_skipped:
return
if self.split_batches:
# Split batches -> the training dataloader batch size is not changed so one step per training step
self.scheduler.step(*lowercase , **lowercase )
else:
# Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
# num_processes steps per training step
UpperCamelCase__ = AcceleratorState().num_processes
for _ in range(lowercase ):
# Special case when using OneCycle and `drop_last` was not used
if hasattr(self.scheduler , """total_steps""" ):
if self.scheduler._step_count <= self.scheduler.total_steps:
self.scheduler.step(*lowercase , **lowercase )
else:
self.scheduler.step(*lowercase , **lowercase )
def A ( self : List[str] ) -> Optional[Any]:
'''simple docstring'''
return self.scheduler.get_last_lr()
def A ( self : Any ) -> int:
'''simple docstring'''
return self.scheduler.state_dict()
def A ( self : Any , lowercase : int ) -> Optional[int]:
'''simple docstring'''
self.scheduler.load_state_dict(lowercase )
def A ( self : str ) -> int:
'''simple docstring'''
return self.scheduler.get_lr()
def A ( self : Union[str, Any] , *lowercase : List[Any] , **lowercase : str ) -> str:
'''simple docstring'''
return self.scheduler.print_lr(*lowercase , **lowercase )
| 265 | 1 |
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {
'configuration_xmod': [
'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP',
'XmodConfig',
'XmodOnnxConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST',
'XmodForCausalLM',
'XmodForMaskedLM',
'XmodForMultipleChoice',
'XmodForQuestionAnswering',
'XmodForSequenceClassification',
'XmodForTokenClassification',
'XmodModel',
'XmodPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xmod import (
XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
XmodForCausalLM,
XmodForMaskedLM,
XmodForMultipleChoice,
XmodForQuestionAnswering,
XmodForSequenceClassification,
XmodForTokenClassification,
XmodModel,
XmodPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 484 |
from dataclasses import asdict, dataclass
from typing import Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__A = logging.get_logger(__name__)
# TODO Update this
__A = {
'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json',
# See all ESM models at https://huggingface.co/models?filter=esm
}
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = "esm"
def __init__( self: Optional[int] , __A: str=None , __A: str=None , __A: Dict=None , __A: List[Any]=7_68 , __A: Union[str, Any]=12 , __A: Any=12 , __A: Optional[int]=30_72 , __A: Optional[Any]=0.1 , __A: str=0.1 , __A: str=10_26 , __A: List[str]=0.02 , __A: Any=1e-12 , __A: List[Any]="absolute" , __A: Optional[Any]=True , __A: int=None , __A: List[str]=False , __A: List[Any]=False , __A: List[Any]=None , __A: Dict=None , **__A: Optional[Any] , ) -> List[Any]:
super().__init__(pad_token_id=__A , mask_token_id=__A , **__A )
_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 = initializer_range
_A = layer_norm_eps
_A = position_embedding_type
_A = use_cache
_A = emb_layer_norm_before
_A = token_dropout
_A = is_folding_model
if is_folding_model:
if esmfold_config is None:
logger.info('''No esmfold_config supplied for folding model, using default values.''' )
_A = EsmFoldConfig()
elif isinstance(__A , __A ):
_A = EsmFoldConfig(**__A )
_A = esmfold_config
if vocab_list is None:
logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' )
_A = get_default_vocab_list()
else:
_A = vocab_list
else:
_A = None
_A = None
if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , __A ):
raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' )
def __A ( self: Dict ) -> Optional[Any]:
_A = super().to_dict()
if isinstance(self.esmfold_config , __A ):
_A = self.esmfold_config.to_dict()
return output
@dataclass
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
A_ = None
A_ = True
A_ = False
A_ = False
A_ = False
A_ = 0
A_ = True
A_ = False
A_ = 128
A_ = None
def __A ( self: Optional[Any] ) -> List[Any]:
if self.trunk is None:
_A = TrunkConfig()
elif isinstance(self.trunk , __A ):
_A = TrunkConfig(**self.trunk )
def __A ( self: Dict ) -> Dict:
_A = asdict(self )
_A = self.trunk.to_dict()
return output
@dataclass
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
A_ = 48
A_ = 1_024
A_ = 128
A_ = 32
A_ = 32
A_ = 32
A_ = 0
A_ = 0
A_ = False
A_ = 4
A_ = 128
A_ = None
def __A ( self: Tuple ) -> Any:
if self.structure_module is None:
_A = StructureModuleConfig()
elif isinstance(self.structure_module , __A ):
_A = StructureModuleConfig(**self.structure_module )
if self.max_recycles <= 0:
raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" )
if self.sequence_state_dim % self.sequence_state_dim != 0:
raise ValueError(
'''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got'''
f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" )
if self.pairwise_state_dim % self.pairwise_state_dim != 0:
raise ValueError(
'''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got'''
f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" )
_A = self.sequence_state_dim // self.sequence_head_width
_A = self.pairwise_state_dim // self.pairwise_head_width
if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
raise ValueError(
'''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got'''
f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" )
if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
raise ValueError(
'''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got'''
f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" )
if self.pairwise_state_dim % 2 != 0:
raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" )
if self.dropout >= 0.4:
raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" )
def __A ( self: List[str] ) -> Optional[int]:
_A = asdict(self )
_A = self.structure_module.to_dict()
return output
@dataclass
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
A_ = 384
A_ = 128
A_ = 16
A_ = 128
A_ = 12
A_ = 4
A_ = 8
A_ = 0.1
A_ = 8
A_ = 1
A_ = 2
A_ = 7
A_ = 10
A_ = 1e-8
A_ = 1e5
def __A ( self: Optional[Any] ) -> str:
return asdict(self )
def __A ( ):
'''simple docstring'''
return (
"<cls>",
"<pad>",
"<eos>",
"<unk>",
"L",
"A",
"G",
"V",
"S",
"E",
"R",
"T",
"I",
"D",
"P",
"K",
"Q",
"N",
"F",
"Y",
"M",
"H",
"W",
"C",
"X",
"B",
"U",
"Z",
"O",
".",
"-",
"<null_1>",
"<mask>",
)
| 484 | 1 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__UpperCAmelCase = logging.get_logger(__name__)
class UpperCamelCase__ ( _snake_case ):
"""simple docstring"""
UpperCAmelCase_ =["pixel_values"]
def __init__( self , _A = True , _A = None , _A = PILImageResampling.BILINEAR , _A = True , _A = None , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = None , **_A , ) -> None:
super().__init__(**lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ = size if size is not None else {'''shortest_edge''': 256}
SCREAMING_SNAKE_CASE_ = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
SCREAMING_SNAKE_CASE_ = get_size_dict(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = resample
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _UpperCamelCase ( self , _A , _A , _A = PILImageResampling.BICUBIC , _A = None , **_A , ) -> np.ndarray:
SCREAMING_SNAKE_CASE_ = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
SCREAMING_SNAKE_CASE_ = get_resize_output_image_size(lowerCAmelCase__ , size=size['''shortest_edge'''] , default_to_square=lowerCAmelCase__ )
return resize(lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , _A , _A , _A = None , **_A , ) -> np.ndarray:
SCREAMING_SNAKE_CASE_ = get_size_dict(lowerCAmelCase__ )
return center_crop(lowerCAmelCase__ , size=(size['''height'''], size['''width''']) , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , _A , _A , _A = None , **_A ) -> np.ndarray:
return rescale(lowerCAmelCase__ , scale=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , _A , _A , _A , _A = None , **_A , ) -> np.ndarray:
return normalize(lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ) -> Dict:
SCREAMING_SNAKE_CASE_ = do_resize if do_resize is not None else self.do_resize
SCREAMING_SNAKE_CASE_ = size if size is not None else self.size
SCREAMING_SNAKE_CASE_ = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ = resample if resample is not None else self.resample
SCREAMING_SNAKE_CASE_ = do_center_crop if do_center_crop is not None else self.do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else self.crop_size
SCREAMING_SNAKE_CASE_ = get_size_dict(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ = do_rescale if do_rescale is not None else self.do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor if rescale_factor is not None else self.rescale_factor
SCREAMING_SNAKE_CASE_ = do_normalize if do_normalize is not None else self.do_normalize
SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else self.image_mean
SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else self.image_std
SCREAMING_SNAKE_CASE_ = make_list_of_images(lowerCAmelCase__ )
if not valid_images(lowerCAmelCase__ ):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''' )
if do_resize and size is None:
raise ValueError('''Size must be specified if do_resize is True.''' )
if do_center_crop and crop_size is None:
raise ValueError('''Crop size must be specified if do_center_crop is True.''' )
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )
# All transformations expect numpy arrays.
SCREAMING_SNAKE_CASE_ = [to_numpy_array(lowerCAmelCase__ ) for image in images]
if do_resize:
SCREAMING_SNAKE_CASE_ = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ ) for image in images]
if do_center_crop:
SCREAMING_SNAKE_CASE_ = [self.center_crop(image=lowerCAmelCase__ , size=lowerCAmelCase__ ) for image in images]
if do_rescale:
SCREAMING_SNAKE_CASE_ = [self.rescale(image=lowerCAmelCase__ , scale=lowerCAmelCase__ ) for image in images]
if do_normalize:
SCREAMING_SNAKE_CASE_ = [self.normalize(image=lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ ) for image in images]
SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ ) for image in images]
SCREAMING_SNAKE_CASE_ = {'''pixel_values''': images}
return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ )
| 701 |
from pathlib import Path
import fire
def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ):
SCREAMING_SNAKE_CASE_ = Path(__lowerCamelCase )
SCREAMING_SNAKE_CASE_ = Path(__lowerCamelCase )
dest_dir.mkdir(exist_ok=__lowerCamelCase )
for path in src_dir.iterdir():
SCREAMING_SNAKE_CASE_ = [x.rstrip() for x in list(path.open().readlines() )][:n]
SCREAMING_SNAKE_CASE_ = dest_dir.joinpath(path.name )
print(__lowerCamelCase )
dest_path.open('''w''' ).write('''\n'''.join(__lowerCamelCase ) )
if __name__ == "__main__":
fire.Fire(minify)
| 597 | 0 |
'''simple docstring'''
import argparse
import os
# New Code #
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils import find_executable_batch_size
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to ensure out-of-memory errors never
# interrupt training, and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
_a : List[str] = 16
_a : Any = 32
def lowerCamelCase__ ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : int = 16 ):
UpperCAmelCase = AutoTokenizer.from_pretrained('bert-base-cased' )
UpperCAmelCase = load_dataset('glue' , 'mrpc' )
def tokenize_function(SCREAMING_SNAKE_CASE : Optional[int] ):
# max_length=None => use the model max length (it's actually the default)
UpperCAmelCase = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
UpperCAmelCase = datasets.map(
UpperCamelCase_ , batched=UpperCamelCase_ , remove_columns=['idx', 'sentence1', 'sentence2'] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
UpperCAmelCase = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(SCREAMING_SNAKE_CASE : str ):
# On TPU it's best to pad everything to the same length or training will be very slow.
UpperCAmelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
UpperCAmelCase = 16
elif accelerator.mixed_precision != "no":
UpperCAmelCase = 8
else:
UpperCAmelCase = None
return tokenizer.pad(
UpperCamelCase_ , padding='longest' , max_length=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_tensors='pt' , )
# Instantiate dataloaders.
UpperCAmelCase = DataLoader(
tokenized_datasets['train'] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ )
UpperCAmelCase = DataLoader(
tokenized_datasets['validation'] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
_a : Dict = mocked_dataloaders # noqa: F811
def lowerCamelCase__ ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[Any] ):
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS' , UpperCamelCase_ ) == "1":
UpperCAmelCase = 2
# Initialize accelerator
UpperCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
UpperCAmelCase = config["""lr"""]
UpperCAmelCase = int(config['num_epochs'] )
UpperCAmelCase = int(config['seed'] )
UpperCAmelCase = int(config['batch_size'] )
UpperCAmelCase = evaluate.load('glue' , 'mrpc' )
# New Code #
# We now can define an inner training loop function. It should take a batch size as the only parameter,
# and build the dataloaders in there.
# It also gets our decorator
@find_executable_batch_size(starting_batch_size=UpperCamelCase_ )
def inner_training_loop(SCREAMING_SNAKE_CASE : List[Any] ):
# And now just move everything below under this function
# We need to bring in the Accelerator object from earlier
nonlocal accelerator
# And reset all of its attributes that could hold onto any memory:
accelerator.free_memory()
# Then we can declare the model, optimizer, and everything else:
set_seed(UpperCamelCase_ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
UpperCAmelCase = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=UpperCamelCase_ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
UpperCAmelCase = model.to(accelerator.device )
# Instantiate optimizer
UpperCAmelCase = AdamW(params=model.parameters() , lr=UpperCamelCase_ )
UpperCAmelCase = get_dataloaders(UpperCamelCase_ , UpperCamelCase_ )
# Instantiate scheduler
UpperCAmelCase = get_linear_schedule_with_warmup(
optimizer=UpperCamelCase_ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase_ ) * num_epochs) , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
UpperCAmelCase = accelerator.prepare(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# Now we train the model
for epoch in range(UpperCamelCase_ ):
model.train()
for step, batch in enumerate(UpperCamelCase_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
UpperCAmelCase = model(**UpperCamelCase_ )
UpperCAmelCase = outputs.loss
accelerator.backward(UpperCamelCase_ )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(UpperCamelCase_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
UpperCAmelCase = model(**UpperCamelCase_ )
UpperCAmelCase = outputs.logits.argmax(dim=-1 )
UpperCAmelCase = accelerator.gather_for_metrics((predictions, batch['labels']) )
metric.add_batch(
predictions=UpperCamelCase_ , references=UpperCamelCase_ , )
UpperCAmelCase = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'''epoch {epoch}:''' , UpperCamelCase_ )
# New Code #
# And call it at the end with no arguments
# Note: You could also refactor this outside of your training loop function
inner_training_loop()
def lowerCamelCase__ ( ):
UpperCAmelCase = argparse.ArgumentParser(description='Simple example of training script.' )
parser.add_argument(
'--mixed_precision' , type=UpperCamelCase_ , default=UpperCamelCase_ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose'
'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
'and an Nvidia Ampere GPU.' , )
parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' )
UpperCAmelCase = parser.parse_args()
UpperCAmelCase = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
training_function(UpperCamelCase_ , UpperCamelCase_ )
if __name__ == "__main__":
main()
| 447 |
import requests
from bsa import BeautifulSoup
def _UpperCAmelCase (UpperCamelCase_ : str = "AAPL" ):
'''simple docstring'''
_lowerCAmelCase : Any = F"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}"
_lowerCAmelCase : Optional[int] = BeautifulSoup(requests.get(UpperCamelCase_ ).text , """html.parser""" )
_lowerCAmelCase : Tuple = """My(6px) Pos(r) smartphone_Mt(6px)"""
return soup.find("""div""" , class_=class_ ).find("""span""" ).text
if __name__ == "__main__":
for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
print(F'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
| 429 | 0 |
'''simple docstring'''
import unittest
from transformers import JukeboxTokenizer
from transformers.testing_utils import require_torch
class UpperCAmelCase__ ( unittest.TestCase ):
lowerCAmelCase_ = JukeboxTokenizer
lowerCAmelCase_ = {
'artist': 'Zac Brown Band',
'genres': 'Country',
'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ',
}
@require_torch
def lowerCamelCase_ ( self : Optional[Any] ):
import torch
_lowerCamelCase : Tuple = JukeboxTokenizer.from_pretrained("openai/jukebox-1b-lyrics" )
_lowerCamelCase : Optional[int] = tokenizer(**self.metas )["input_ids"]
# fmt: off
_lowerCamelCase : List[str] = [
torch.tensor([[
0, 0, 0, 7_1_6_9, 5_0_7, 9, 7_6, 3_9, 3_1, 4_6, 7_6, 2_7,
7_6, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_6, 3_2,
4_4, 4_1, 3_9, 7_6, 2_7, 4_0, 7_6, 2_7, 4_0, 4_6, 3_5, 4_3,
4_7, 3_1, 7_6, 3_8, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6,
7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 4_1, 7_6, 4_5, 2_7, 3_5,
3_0, 7_6, 7_1, 2_0, 4_9, 4_1, 7_6, 4_8, 2_7, 4_5, 4_6, 7_6,
2_7, 4_0, 3_0, 7_6, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5,
4_5, 7_6, 3_8, 3_1, 3_3, 4_5, 7_6, 4_1, 3_2, 7_6, 4_5, 4_6,
4_1, 4_0, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6,
1_9, 4_6, 2_7, 4_0, 3_0, 7_6, 3_5, 4_0, 7_6, 4_6, 3_4, 3_1,
7_6, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_6, 6_3, 7_6, 6_3,
7_6, 6_3, 7_6, 1_4, 3_1, 2_7, 4_4, 7_6, 4_6, 3_4, 3_1, 3_9,
6_4, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_5, 2_7, 4_0,
3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 8,
2_7, 3_8, 3_2, 7_6, 4_5, 4_7, 4_0, 3_7, 7_6, 2_7, 7_6, 4_5,
3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_6, 4_8, 3_5, 4_5,
2_7, 3_3, 3_1, 7_6, 3_8, 3_5, 3_1, 4_5, 6_4, 7_6, 4_9, 3_4,
4_1, 4_5, 3_1, 7_6, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_8, 7_6,
7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_9,
4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_6, 3_8, 3_5, 4_2, 6_4,
7_6, 2_7, 4_0, 3_0, 7_6, 4_5, 4_0, 3_1, 3_1, 4_4, 7_6, 4_1,
3_2, 7_6, 2_9, 4_1, 3_8, 3_0, 7_6, 2_9, 4_1, 3_9, 3_9, 2_7,
4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6,
2_0, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_5, 4_6,
4_5, 7_6, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_6, 4_9,
3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 4_1, 4_5, 3_1, 7_6, 4_2, 2_7,
4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_6, 4_4, 3_1, 2_7, 3_0, 7_8,
7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 3_5, 2_9,
3_4, 7_6, 5_1, 3_1, 4_6, 7_6, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8,
3_1, 6_4, 7_6, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_6, 4_1,
4_0, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 3_8, 3_5, 3_2, 3_1,
3_8, 3_1, 4_5, 4_5, 7_6, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4,
7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1,
7_6, 3_4, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_9,
4_1, 2_9, 3_7, 3_1, 3_0, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6,
2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_4, 3_1, 2_7, 4_4,
4_6, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_2, 3_1, 3_0, 6_6, 7_8,
7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6,
4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_2, 3_1, 3_0, 3_1, 4_5,
4_6, 2_7, 3_8, 6_4, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 4_9,
4_1, 4_4, 3_0, 4_5, 7_6, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5,
7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_3, 5_1, 7_6,
4_0, 2_7, 3_9, 3_1, 7_6, 3_5, 4_5, 7_6, 1_5, 5_2, 5_1, 3_9,
2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_6, 1_1, 3_5, 4_0, 3_3,
7_6, 4_1, 3_2, 7_6, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_8, 7_6,
7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_2, 4_1, 4_1, 3_7, 7_6,
4_1, 4_0, 7_6, 3_9, 5_1, 7_6, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4,
7_6, 5_1, 3_1, 7_6, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_6,
2_7, 4_0, 3_0, 7_6, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7,
7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_4, 4_1, 4_6,
3_4, 3_5, 4_0, 3_3, 7_6, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_6,
4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_6, 1_8, 4_1, 4_7,
4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 2_9, 2_7, 5_1,
7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_5, 3_2, 7_6,
4_6, 3_4, 2_7, 4_6, 7_6, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7,
3_8, 7_6, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_6, 2_8, 4_1, 4_7,
4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_6, 2_7, 4_0, 3_0, 7_6, 2_8,
2_7, 4_4, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6,
2_0, 3_4, 3_1, 7_6, 3_8, 4_1, 4_0, 3_1, 7_6, 2_7, 4_0, 3_0,
7_6, 3_8, 3_1, 4_8, 3_1, 3_8, 7_6, 4_5, 2_7, 4_0, 3_0, 4_5,
7_6, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_6, 3_2, 2_7, 4_4,
7_6, 2_7, 4_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6,
7_6, 7_6]] ),
torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ),
torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ),
]
# fmt: on
self.assertTrue(torch.allclose(tokens[0],EXPECTED_OUTPUT[0] ) )
self.assertTrue(torch.allclose(tokens[1],EXPECTED_OUTPUT[1] ) )
self.assertTrue(torch.allclose(tokens[2],EXPECTED_OUTPUT[2] ) )
@require_torch
def lowerCamelCase_ ( self : Optional[Any] ):
import torch
_lowerCamelCase : Tuple = JukeboxTokenizer.from_pretrained("openai/jukebox-5b-lyrics" )
_lowerCamelCase : List[str] = tokenizer(**self.metas )["input_ids"]
# fmt: off
_lowerCamelCase : int = [
torch.tensor([[
0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1, 9, 7_7, 3_9,
3_1, 4_6, 7_7, 2_7, 7_7, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8,
3_1, 4_4, 7_7, 3_2, 4_4, 4_1, 3_9, 7_7, 2_7, 4_0, 7_7, 2_7,
4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_7, 3_8, 2_7, 4_0, 3_0, 6_4,
7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 4_1,
7_7, 4_5, 2_7, 3_5, 3_0, 7_7, 7_2, 2_0, 4_9, 4_1, 7_7, 4_8,
2_7, 4_5, 4_6, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 4_4, 4_7, 4_0,
3_7, 3_8, 3_1, 4_5, 4_5, 7_7, 3_8, 3_1, 3_3, 4_5, 7_7, 4_1,
3_2, 7_7, 4_5, 4_6, 4_1, 4_0, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7,
7_7, 7_7, 7_7, 7_7, 1_9, 4_6, 2_7, 4_0, 3_0, 7_7, 3_5, 4_0,
7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3,
7_7, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 1_4, 3_1, 2_7, 4_4, 7_7,
4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1,
7_7, 4_5, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7,
7_7, 7_7, 7_7, 8, 2_7, 3_8, 3_2, 7_7, 4_5, 4_7, 4_0, 3_7,
7_7, 2_7, 7_7, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0,
7_7, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_7, 3_8, 3_5, 3_1, 4_5,
6_4, 7_7, 4_9, 3_4, 4_1, 4_5, 3_1, 7_7, 3_2, 4_4, 4_1, 4_9,
4_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1,
4_0, 3_0, 7_7, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_7,
3_8, 3_5, 4_2, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_5, 4_0, 3_1,
3_1, 4_4, 7_7, 4_1, 3_2, 7_7, 2_9, 4_1, 3_8, 3_0, 7_7, 2_9,
4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7,
7_7, 7_7, 7_7, 7_7, 2_0, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 2_7,
4_6, 7_7, 3_5, 4_6, 4_5, 7_7, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6,
4_1, 4_4, 7_7, 4_9, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 4_1, 4_5,
3_1, 7_7, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_7, 4_4,
3_1, 2_7, 3_0, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7,
2_3, 3_4, 3_5, 2_9, 3_4, 7_7, 5_1, 3_1, 4_6, 7_7, 4_5, 4_7,
4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_7, 4_5, 4_6, 2_7, 3_9, 4_2,
3_1, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7,
3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_7, 4_6, 3_4, 3_5,
4_0, 3_3, 4_5, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7,
7_7, 2_0, 3_4, 3_1, 7_7, 3_4, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4,
2_7, 4_6, 7_7, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_7, 4_6, 3_4,
3_1, 3_9, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7,
3_4, 3_1, 2_7, 4_4, 4_6, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_2,
3_1, 3_0, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7,
1, 4_0, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_2,
3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_7, 4_6, 3_4, 3_1,
4_5, 3_1, 7_7, 4_9, 4_1, 4_4, 3_0, 4_5, 7_7, 2_7, 4_2, 4_2,
3_1, 2_7, 4_4, 6_5, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7,
7_7, 1_3, 5_1, 7_7, 4_0, 2_7, 3_9, 3_1, 7_7, 3_5, 4_5, 7_7,
1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_7,
1_1, 3_5, 4_0, 3_3, 7_7, 4_1, 3_2, 7_7, 1_1, 3_5, 4_0, 3_3,
4_5, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_2,
4_1, 4_1, 3_7, 7_7, 4_1, 4_0, 7_7, 3_9, 5_1, 7_7, 2_3, 4_1,
4_4, 3_7, 4_5, 6_4, 7_7, 5_1, 3_1, 7_7, 1_3, 3_5, 3_3, 3_4,
4_6, 5_1, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 3_0, 3_1, 4_5, 4_2,
2_7, 3_5, 4_4, 6_7, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7,
7_7, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_7, 2_8, 3_1, 4_5,
3_5, 3_0, 3_1, 7_7, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3,
7_7, 1_8, 4_1, 4_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0,
3_1, 2_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7,
7_7, 1_5, 3_2, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 2_9, 4_1, 3_8,
4_1, 4_5, 4_5, 2_7, 3_8, 7_7, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4,
7_7, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_7, 2_7,
4_0, 3_0, 7_7, 2_8, 2_7, 4_4, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7,
7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_8, 4_1, 4_0, 3_1,
7_7, 2_7, 4_0, 3_0, 7_7, 3_8, 3_1, 4_8, 3_1, 3_8, 7_7, 4_5,
2_7, 4_0, 3_0, 4_5, 7_7, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4,
7_7, 3_2, 2_7, 4_4, 7_7, 2_7, 4_9, 2_7, 5_1, 7_9, 7_7, 7_7,
7_7, 7_7, 7_7, 7_7, 7_7, 7_7]] ),
torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ),
torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ),
]
# fmt: on
self.assertTrue(torch.allclose(tokens[0],EXPECTED_OUTPUT[0] ) )
self.assertTrue(torch.allclose(tokens[1],EXPECTED_OUTPUT[1] ) )
self.assertTrue(torch.allclose(tokens[2],EXPECTED_OUTPUT[2] ) ) | 11 |
'''simple docstring'''
import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union
import numpy as np
import torch
from .utils import deprecate, is_transformers_available
if is_transformers_available():
import transformers
def A_ ( _lowerCAmelCase : int ):
"""simple docstring"""
random.seed(_lowerCAmelCase )
np.random.seed(_lowerCAmelCase )
torch.manual_seed(_lowerCAmelCase )
torch.cuda.manual_seed_all(_lowerCAmelCase )
# ^^ safe to call this function even if cuda is not available
class UpperCAmelCase__ :
def __init__( self : List[str],__A : Iterable[torch.nn.Parameter],__A : float = 0.9999,__A : float = 0.0,__A : int = 0,__A : bool = False,__A : Union[float, int] = 1.0,__A : Union[float, int] = 2 / 3,__A : Optional[Any] = None,__A : Dict[str, Any] = None,**__A : Optional[Any],):
if isinstance(__A,torch.nn.Module ):
_lowerCamelCase : Any = (
"Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. "
"Please pass the parameters of the module instead."
)
deprecate(
"passing a `torch.nn.Module` to `ExponentialMovingAverage`","1.0.0",__A,standard_warn=__A,)
_lowerCamelCase : Dict = parameters.parameters()
# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
_lowerCamelCase : Optional[Any] = True
if kwargs.get("max_value",__A ) is not None:
_lowerCamelCase : Optional[int] = "The `max_value` argument is deprecated. Please use `decay` instead."
deprecate("max_value","1.0.0",__A,standard_warn=__A )
_lowerCamelCase : Optional[Any] = kwargs["max_value"]
if kwargs.get("min_value",__A ) is not None:
_lowerCamelCase : Tuple = "The `min_value` argument is deprecated. Please use `min_decay` instead."
deprecate("min_value","1.0.0",__A,standard_warn=__A )
_lowerCamelCase : Any = kwargs["min_value"]
_lowerCamelCase : Optional[int] = list(__A )
_lowerCamelCase : List[Any] = [p.clone().detach() for p in parameters]
if kwargs.get("device",__A ) is not None:
_lowerCamelCase : Optional[int] = "The `device` argument is deprecated. Please use `to` instead."
deprecate("device","1.0.0",__A,standard_warn=__A )
self.to(device=kwargs["device"] )
_lowerCamelCase : Tuple = None
_lowerCamelCase : Dict = decay
_lowerCamelCase : List[Any] = min_decay
_lowerCamelCase : Optional[Any] = update_after_step
_lowerCamelCase : Any = use_ema_warmup
_lowerCamelCase : Union[str, Any] = inv_gamma
_lowerCamelCase : str = power
_lowerCamelCase : Union[str, Any] = 0
_lowerCamelCase : Union[str, Any] = None # set in `step()`
_lowerCamelCase : List[str] = model_cls
_lowerCamelCase : Dict = model_config
@classmethod
def lowerCamelCase_ ( cls : Union[str, Any],__A : List[str],__A : Optional[int] ):
_lowerCamelCase , _lowerCamelCase : Optional[int] = model_cls.load_config(__A,return_unused_kwargs=__A )
_lowerCamelCase : Optional[Any] = model_cls.from_pretrained(__A )
_lowerCamelCase : Union[str, Any] = cls(model.parameters(),model_cls=__A,model_config=model.config )
ema_model.load_state_dict(__A )
return ema_model
def lowerCamelCase_ ( self : str,__A : int ):
if self.model_cls is None:
raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__." )
if self.model_config is None:
raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__." )
_lowerCamelCase : Tuple = self.model_cls.from_config(self.model_config )
_lowerCamelCase : List[str] = self.state_dict()
state_dict.pop("shadow_params",__A )
model.register_to_config(**__A )
self.copy_to(model.parameters() )
model.save_pretrained(__A )
def lowerCamelCase_ ( self : Optional[int],__A : int ):
_lowerCamelCase : str = max(0,optimization_step - self.update_after_step - 1 )
if step <= 0:
return 0.0
if self.use_ema_warmup:
_lowerCamelCase : Tuple = 1 - (1 + step / self.inv_gamma) ** -self.power
else:
_lowerCamelCase : List[str] = (1 + step) / (1_0 + step)
_lowerCamelCase : Union[str, Any] = min(__A,self.decay )
# make sure decay is not smaller than min_decay
_lowerCamelCase : Union[str, Any] = max(__A,self.min_decay )
return cur_decay_value
@torch.no_grad()
def lowerCamelCase_ ( self : Any,__A : Iterable[torch.nn.Parameter] ):
if isinstance(__A,torch.nn.Module ):
_lowerCamelCase : Dict = (
"Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. "
"Please pass the parameters of the module instead."
)
deprecate(
"passing a `torch.nn.Module` to `ExponentialMovingAverage.step`","1.0.0",__A,standard_warn=__A,)
_lowerCamelCase : Any = parameters.parameters()
_lowerCamelCase : str = list(__A )
self.optimization_step += 1
# Compute the decay factor for the exponential moving average.
_lowerCamelCase : Dict = self.get_decay(self.optimization_step )
_lowerCamelCase : Optional[Any] = decay
_lowerCamelCase : List[Any] = 1 - decay
_lowerCamelCase : List[Any] = contextlib.nullcontext
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
import deepspeed
for s_param, param in zip(self.shadow_params,__A ):
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
_lowerCamelCase : List[Any] = deepspeed.zero.GatheredParameters(__A,modifier_rank=__A )
with context_manager():
if param.requires_grad:
s_param.sub_(one_minus_decay * (s_param - param) )
else:
s_param.copy_(__A )
def lowerCamelCase_ ( self : Dict,__A : Iterable[torch.nn.Parameter] ):
_lowerCamelCase : Tuple = list(__A )
for s_param, param in zip(self.shadow_params,__A ):
param.data.copy_(s_param.to(param.device ).data )
def lowerCamelCase_ ( self : List[str],__A : Dict=None,__A : Any=None ):
_lowerCamelCase : int = [
p.to(device=__A,dtype=__A ) if p.is_floating_point() else p.to(device=__A )
for p in self.shadow_params
]
def lowerCamelCase_ ( self : List[Any] ):
return {
"decay": self.decay,
"min_decay": self.min_decay,
"optimization_step": self.optimization_step,
"update_after_step": self.update_after_step,
"use_ema_warmup": self.use_ema_warmup,
"inv_gamma": self.inv_gamma,
"power": self.power,
"shadow_params": self.shadow_params,
}
def lowerCamelCase_ ( self : Tuple,__A : Iterable[torch.nn.Parameter] ):
_lowerCamelCase : Tuple = [param.detach().cpu().clone() for param in parameters]
def lowerCamelCase_ ( self : int,__A : Iterable[torch.nn.Parameter] ):
if self.temp_stored_params is None:
raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights " "to `restore()`" )
for c_param, param in zip(self.temp_stored_params,__A ):
param.data.copy_(c_param.data )
# Better memory-wise.
_lowerCamelCase : List[str] = None
def lowerCamelCase_ ( self : Dict,__A : dict ):
_lowerCamelCase : List[str] = copy.deepcopy(__A )
_lowerCamelCase : Optional[Any] = state_dict.get("decay",self.decay )
if self.decay < 0.0 or self.decay > 1.0:
raise ValueError("Decay must be between 0 and 1" )
_lowerCamelCase : Dict = state_dict.get("min_decay",self.min_decay )
if not isinstance(self.min_decay,__A ):
raise ValueError("Invalid min_decay" )
_lowerCamelCase : Tuple = state_dict.get("optimization_step",self.optimization_step )
if not isinstance(self.optimization_step,__A ):
raise ValueError("Invalid optimization_step" )
_lowerCamelCase : Any = state_dict.get("update_after_step",self.update_after_step )
if not isinstance(self.update_after_step,__A ):
raise ValueError("Invalid update_after_step" )
_lowerCamelCase : List[Any] = state_dict.get("use_ema_warmup",self.use_ema_warmup )
if not isinstance(self.use_ema_warmup,__A ):
raise ValueError("Invalid use_ema_warmup" )
_lowerCamelCase : Tuple = state_dict.get("inv_gamma",self.inv_gamma )
if not isinstance(self.inv_gamma,(float, int) ):
raise ValueError("Invalid inv_gamma" )
_lowerCamelCase : Union[str, Any] = state_dict.get("power",self.power )
if not isinstance(self.power,(float, int) ):
raise ValueError("Invalid power" )
_lowerCamelCase : Optional[Any] = state_dict.get("shadow_params",__A )
if shadow_params is not None:
_lowerCamelCase : str = shadow_params
if not isinstance(self.shadow_params,__A ):
raise ValueError("shadow_params must be a list" )
if not all(isinstance(__A,torch.Tensor ) for p in self.shadow_params ):
raise ValueError("shadow_params must all be Tensors" ) | 11 | 1 |
'''simple docstring'''
def _snake_case ( _SCREAMING_SNAKE_CASE : int ) -> Tuple:
"""simple docstring"""
if number < 0:
raise ValueError("""number must not be negative""" )
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod() | 433 |
'''simple docstring'''
import requests
_SCREAMING_SNAKE_CASE = '''YOUR API KEY'''
def _lowerCAmelCase ( lowerCamelCase_ : str , lowerCamelCase_ : str = giphy_api_key ):
__lowercase = '''+'''.join(query.split() )
__lowercase = f"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}"
__lowercase = requests.get(lowerCamelCase_ ).json()['''data''']
return [gif["url"] for gif in gifs]
if __name__ == "__main__":
print('''\n'''.join(get_gifs('''space ship''')))
| 502 | 0 |
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
lowercase : Tuple = logging.get_logger(__name__)
lowercase : Tuple = {
"""salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""",
}
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = "blip_2_vision_model"
def __init__( self : str , A_ : List[str]=14_08 , A_ : Tuple=61_44 , A_ : str=39 , A_ : Optional[Any]=16 , A_ : Tuple=2_24 , A_ : List[Any]=14 , A_ : Optional[int]="gelu" , A_ : Optional[Any]=0.00001 , A_ : List[Any]=0.0 , A_ : int=1e-10 , A_ : List[str]=True , **A_ : Dict , ) -> Optional[Any]:
"""simple docstring"""
super().__init__(**A_ )
lowerCamelCase_: Dict = hidden_size
lowerCamelCase_: Optional[Any] = intermediate_size
lowerCamelCase_: Optional[Any] = num_hidden_layers
lowerCamelCase_: Dict = num_attention_heads
lowerCamelCase_: List[str] = patch_size
lowerCamelCase_: List[Any] = image_size
lowerCamelCase_: Optional[int] = initializer_range
lowerCamelCase_: List[str] = attention_dropout
lowerCamelCase_: Tuple = layer_norm_eps
lowerCamelCase_: List[Any] = hidden_act
lowerCamelCase_: int = qkv_bias
@classmethod
def lowerCAmelCase ( cls : Optional[Any] , A_ : Union[str, os.PathLike] , **A_ : Dict ) -> "PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(A_ )
lowerCamelCase_ , lowerCamelCase_: List[str] = cls.get_config_dict(A_ , **A_ )
# get the vision config dict if we are loading from Blip2Config
if config_dict.get("""model_type""" ) == "blip-2":
lowerCamelCase_: Union[str, Any] = config_dict["""vision_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )
return cls.from_dict(A_ , **A_ )
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = "blip_2_qformer"
def __init__( self : Any , A_ : int=3_05_22 , A_ : Union[str, Any]=7_68 , A_ : Any=12 , A_ : Optional[int]=12 , A_ : str=30_72 , A_ : Optional[int]="gelu" , A_ : str=0.1 , A_ : List[str]=0.1 , A_ : Any=5_12 , A_ : str=0.02 , A_ : str=1e-12 , A_ : Optional[int]=0 , A_ : Any="absolute" , A_ : int=2 , A_ : Optional[Any]=14_08 , **A_ : Union[str, Any] , ) -> int:
"""simple docstring"""
super().__init__(pad_token_id=A_ , **A_ )
lowerCamelCase_: Tuple = vocab_size
lowerCamelCase_: List[str] = hidden_size
lowerCamelCase_: int = num_hidden_layers
lowerCamelCase_: Dict = num_attention_heads
lowerCamelCase_: Union[str, Any] = hidden_act
lowerCamelCase_: Tuple = intermediate_size
lowerCamelCase_: List[str] = hidden_dropout_prob
lowerCamelCase_: List[str] = attention_probs_dropout_prob
lowerCamelCase_: Dict = max_position_embeddings
lowerCamelCase_: Optional[Any] = initializer_range
lowerCamelCase_: Dict = layer_norm_eps
lowerCamelCase_: Tuple = position_embedding_type
lowerCamelCase_: str = cross_attention_frequency
lowerCamelCase_: int = encoder_hidden_size
@classmethod
def lowerCAmelCase ( cls : Any , A_ : Union[str, os.PathLike] , **A_ : Any ) -> "PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(A_ )
lowerCamelCase_ , lowerCamelCase_: List[Any] = cls.get_config_dict(A_ , **A_ )
# get the qformer config dict if we are loading from Blip2Config
if config_dict.get("""model_type""" ) == "blip-2":
lowerCamelCase_: Dict = config_dict["""qformer_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )
return cls.from_dict(A_ , **A_ )
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = "blip-2"
_A = True
def __init__( self : Optional[int] , A_ : Tuple=None , A_ : Union[str, Any]=None , A_ : List[Any]=None , A_ : Tuple=32 , **A_ : Any ) -> Any:
"""simple docstring"""
super().__init__(**A_ )
if vision_config is None:
lowerCamelCase_: Dict = {}
logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" )
if qformer_config is None:
lowerCamelCase_: Optional[int] = {}
logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" )
if text_config is None:
lowerCamelCase_: Any = {}
logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" )
lowerCamelCase_: Any = BlipaVisionConfig(**A_ )
lowerCamelCase_: Optional[int] = BlipaQFormerConfig(**A_ )
lowerCamelCase_: List[Any] = text_config["""model_type"""] if """model_type""" in text_config else """opt"""
lowerCamelCase_: Optional[int] = CONFIG_MAPPING[text_model_type](**A_ )
lowerCamelCase_: List[str] = self.text_config.tie_word_embeddings
lowerCamelCase_: int = self.text_config.is_encoder_decoder
lowerCamelCase_: Any = num_query_tokens
lowerCamelCase_: Tuple = self.vision_config.hidden_size
lowerCamelCase_: str = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
lowerCamelCase_: int = 1.0
lowerCamelCase_: Dict = 0.02
@classmethod
def lowerCAmelCase ( cls : Union[str, Any] , A_ : BlipaVisionConfig , A_ : BlipaQFormerConfig , A_ : PretrainedConfig , **A_ : Dict , ) -> Tuple:
"""simple docstring"""
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , )
def lowerCAmelCase ( self : Any ) -> Any:
"""simple docstring"""
lowerCamelCase_: Tuple = copy.deepcopy(self.__dict__ )
lowerCamelCase_: Any = self.vision_config.to_dict()
lowerCamelCase_: Optional[Any] = self.qformer_config.to_dict()
lowerCamelCase_: List[str] = self.text_config.to_dict()
lowerCamelCase_: Optional[Any] = self.__class__.model_type
return output
| 584 | import torch
from diffusers import EulerDiscreteScheduler
from diffusers.utils import torch_device
from .test_schedulers import SchedulerCommonTest
class a__ ( __SCREAMING_SNAKE_CASE ):
_A = (EulerDiscreteScheduler,)
_A = 10
def lowerCAmelCase ( self : Optional[Any] , **A_ : str ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase_: Tuple = {
"""num_train_timesteps""": 11_00,
"""beta_start""": 0.0001,
"""beta_end""": 0.02,
"""beta_schedule""": """linear""",
}
config.update(**A_ )
return config
def lowerCAmelCase ( self : Optional[Any] ) -> int:
"""simple docstring"""
for timesteps in [10, 50, 1_00, 10_00]:
self.check_over_configs(num_train_timesteps=A_ )
def lowerCAmelCase ( self : Optional[Any] ) -> List[str]:
"""simple docstring"""
for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ):
self.check_over_configs(beta_start=A_ , beta_end=A_ )
def lowerCAmelCase ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
for schedule in ["linear", "scaled_linear"]:
self.check_over_configs(beta_schedule=A_ )
def lowerCAmelCase ( self : Dict ) -> List[str]:
"""simple docstring"""
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=A_ )
def lowerCAmelCase ( self : List[str] ) -> List[str]:
"""simple docstring"""
lowerCamelCase_: Any = self.scheduler_classes[0]
lowerCamelCase_: Optional[int] = self.get_scheduler_config()
lowerCamelCase_: Tuple = scheduler_class(**A_ )
scheduler.set_timesteps(self.num_inference_steps )
lowerCamelCase_: Optional[Any] = torch.manual_seed(0 )
lowerCamelCase_: Optional[Any] = self.dummy_model()
lowerCamelCase_: List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma
lowerCamelCase_: Optional[int] = sample.to(A_ )
for i, t in enumerate(scheduler.timesteps ):
lowerCamelCase_: Dict = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: Tuple = model(A_ , A_ )
lowerCamelCase_: int = scheduler.step(A_ , A_ , A_ , generator=A_ )
lowerCamelCase_: Union[str, Any] = output.prev_sample
lowerCamelCase_: int = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: int = torch.mean(torch.abs(A_ ) )
assert abs(result_sum.item() - 10.0807 ) < 1e-2
assert abs(result_mean.item() - 0.0131 ) < 1e-3
def lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase_: Optional[int] = self.scheduler_classes[0]
lowerCamelCase_: Dict = self.get_scheduler_config(prediction_type="""v_prediction""" )
lowerCamelCase_: Any = scheduler_class(**A_ )
scheduler.set_timesteps(self.num_inference_steps )
lowerCamelCase_: Any = torch.manual_seed(0 )
lowerCamelCase_: Dict = self.dummy_model()
lowerCamelCase_: Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma
lowerCamelCase_: Any = sample.to(A_ )
for i, t in enumerate(scheduler.timesteps ):
lowerCamelCase_: int = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: Optional[Any] = model(A_ , A_ )
lowerCamelCase_: List[str] = scheduler.step(A_ , A_ , A_ , generator=A_ )
lowerCamelCase_: str = output.prev_sample
lowerCamelCase_: int = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: List[Any] = torch.mean(torch.abs(A_ ) )
assert abs(result_sum.item() - 0.0002 ) < 1e-2
assert abs(result_mean.item() - 2.26_76e-06 ) < 1e-3
def lowerCAmelCase ( self : int ) -> int:
"""simple docstring"""
lowerCamelCase_: Any = self.scheduler_classes[0]
lowerCamelCase_: Optional[Any] = self.get_scheduler_config()
lowerCamelCase_: int = scheduler_class(**A_ )
scheduler.set_timesteps(self.num_inference_steps , device=A_ )
lowerCamelCase_: Dict = torch.manual_seed(0 )
lowerCamelCase_: Union[str, Any] = self.dummy_model()
lowerCamelCase_: str = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
lowerCamelCase_: str = sample.to(A_ )
for t in scheduler.timesteps:
lowerCamelCase_: str = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: str = model(A_ , A_ )
lowerCamelCase_: List[Any] = scheduler.step(A_ , A_ , A_ , generator=A_ )
lowerCamelCase_: int = output.prev_sample
lowerCamelCase_: List[Any] = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: Optional[int] = torch.mean(torch.abs(A_ ) )
assert abs(result_sum.item() - 10.0807 ) < 1e-2
assert abs(result_mean.item() - 0.0131 ) < 1e-3
def lowerCAmelCase ( self : Any ) -> Any:
"""simple docstring"""
lowerCamelCase_: Any = self.scheduler_classes[0]
lowerCamelCase_: Dict = self.get_scheduler_config()
lowerCamelCase_: int = scheduler_class(**A_ , use_karras_sigmas=A_ )
scheduler.set_timesteps(self.num_inference_steps , device=A_ )
lowerCamelCase_: List[str] = torch.manual_seed(0 )
lowerCamelCase_: Union[str, Any] = self.dummy_model()
lowerCamelCase_: Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
lowerCamelCase_: List[str] = sample.to(A_ )
for t in scheduler.timesteps:
lowerCamelCase_: int = scheduler.scale_model_input(A_ , A_ )
lowerCamelCase_: int = model(A_ , A_ )
lowerCamelCase_: List[Any] = scheduler.step(A_ , A_ , A_ , generator=A_ )
lowerCamelCase_: List[Any] = output.prev_sample
lowerCamelCase_: Optional[int] = torch.sum(torch.abs(A_ ) )
lowerCamelCase_: int = torch.mean(torch.abs(A_ ) )
assert abs(result_sum.item() - 124.52299499511719 ) < 1e-2
assert abs(result_mean.item() - 0.16213932633399963 ) < 1e-3
| 584 | 1 |
"""simple docstring"""
# using dfs for finding eulerian path traversal
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = (path or []) + [u]
for v in graph[u]:
if visited_edge[u][v] is False:
UpperCAmelCase__ , UpperCAmelCase__ : List[str] = True, True
UpperCAmelCase__ : Any = dfs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
return path
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
'''simple docstring'''
UpperCAmelCase__ : str = 0
UpperCAmelCase__ : Union[str, Any] = -1
for i in range(__UpperCamelCase ):
if i not in graph.keys():
continue
if len(graph[i] ) % 2 == 1:
odd_degree_nodes += 1
UpperCAmelCase__ : str = i
if odd_degree_nodes == 0:
return 1, odd_node
if odd_degree_nodes == 2:
return 2, odd_node
return 3, odd_node
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )]
UpperCAmelCase__ , UpperCAmelCase__ : int = check_circuit_or_path(__UpperCamelCase , __UpperCamelCase )
if check == 3:
print("""graph is not Eulerian""" )
print("""no path""" )
return
UpperCAmelCase__ : Dict = 1
if check == 2:
UpperCAmelCase__ : List[str] = odd_node
print("""graph has a Euler path""" )
if check == 1:
print("""graph has a Euler cycle""" )
UpperCAmelCase__ : str = dfs(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
print(__UpperCamelCase )
def lowerCAmelCase ( ):
'''simple docstring'''
UpperCAmelCase__ : str = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
UpperCAmelCase__ : List[str] = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
UpperCAmelCase__ : Union[str, Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
UpperCAmelCase__ : Optional[Any] = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
UpperCAmelCase__ : List[str] = {
1: [],
2: []
# all degree is zero
}
UpperCAmelCase__ : Dict = 10
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
check_euler(__UpperCamelCase , __UpperCamelCase )
if __name__ == "__main__":
main()
| 65 |
"""simple docstring"""
import unittest
import numpy as np
from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.distilbert.modeling_flax_distilbert import (
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertModel,
)
class __lowercase ( unittest.TestCase ):
def __init__( self : Union[str, Any] ,A : Optional[int] ,A : int=13 ,A : Tuple=7 ,A : Dict=True ,A : Optional[int]=True ,A : Tuple=True ,A : str=True ,A : Any=99 ,A : Tuple=32 ,A : Dict=5 ,A : Optional[int]=4 ,A : Dict=37 ,A : Any="gelu" ,A : Any=0.1 ,A : Optional[int]=0.1 ,A : Union[str, Any]=512 ,A : Any=16 ,A : List[str]=2 ,A : List[Any]=0.0_2 ,A : Optional[int]=4 ,):
'''simple docstring'''
UpperCAmelCase__ : Dict = parent
UpperCAmelCase__ : Any = batch_size
UpperCAmelCase__ : List[Any] = seq_length
UpperCAmelCase__ : Optional[int] = is_training
UpperCAmelCase__ : Optional[Any] = use_attention_mask
UpperCAmelCase__ : int = use_token_type_ids
UpperCAmelCase__ : int = use_labels
UpperCAmelCase__ : Any = vocab_size
UpperCAmelCase__ : Union[str, Any] = hidden_size
UpperCAmelCase__ : int = num_hidden_layers
UpperCAmelCase__ : int = num_attention_heads
UpperCAmelCase__ : Dict = intermediate_size
UpperCAmelCase__ : Any = hidden_act
UpperCAmelCase__ : Union[str, Any] = hidden_dropout_prob
UpperCAmelCase__ : Any = attention_probs_dropout_prob
UpperCAmelCase__ : str = max_position_embeddings
UpperCAmelCase__ : List[Any] = type_vocab_size
UpperCAmelCase__ : List[str] = type_sequence_label_size
UpperCAmelCase__ : List[Any] = initializer_range
UpperCAmelCase__ : List[Any] = num_choices
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase__ : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
UpperCAmelCase__ : List[str] = None
if self.use_attention_mask:
UpperCAmelCase__ : str = random_attention_mask([self.batch_size, self.seq_length] )
UpperCAmelCase__ : int = DistilBertConfig(
vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=A ,)
return config, input_ids, attention_mask
def __lowercase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs()
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Any = config_and_inputs
UpperCAmelCase__ : str = {"""input_ids""": input_ids, """attention_mask""": attention_mask}
return config, inputs_dict
@require_flax
class __lowercase ( __lowerCamelCase , unittest.TestCase ):
snake_case_ = (
(
FlaxDistilBertModel,
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
UpperCAmelCase__ : List[str] = FlaxDistilBertModelTester(self )
@slow
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
for model_class_name in self.all_model_classes:
UpperCAmelCase__ : Union[str, Any] = model_class_name.from_pretrained("""distilbert-base-uncased""" )
UpperCAmelCase__ : List[Any] = model(np.ones((1, 1) ) )
self.assertIsNotNone(A )
@require_flax
class __lowercase ( unittest.TestCase ):
@slow
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase__ : Union[str, Any] = FlaxDistilBertModel.from_pretrained("""distilbert-base-uncased""" )
UpperCAmelCase__ : List[Any] = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
UpperCAmelCase__ : str = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
UpperCAmelCase__ : Dict = model(A ,attention_mask=A )[0]
UpperCAmelCase__ : List[Any] = (1, 11, 768)
self.assertEqual(output.shape ,A )
UpperCAmelCase__ : Any = np.array([[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]] )
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,A ,atol=1e-4 ) )
| 65 | 1 |
"""simple docstring"""
from .testing import (
are_the_same_tensors,
execute_subprocess_async,
require_bnb,
require_cpu,
require_cuda,
require_huggingface_suite,
require_mps,
require_multi_gpu,
require_multi_xpu,
require_safetensors,
require_single_gpu,
require_single_xpu,
require_torch_min_version,
require_tpu,
require_xpu,
skip,
slow,
)
from .training import RegressionDataset, RegressionModel, RegressionModelaXPU
from .scripts import test_script, test_sync, test_ops # isort: skip
| 681 |
"""simple docstring"""
def a__ ( SCREAMING_SNAKE_CASE : List[str] ):
'''simple docstring'''
lowerCAmelCase : Optional[int] = len(SCREAMING_SNAKE_CASE )
while cur > 1:
# Find the maximum number in arr
lowerCAmelCase : List[str] = arr.index(max(arr[0:cur] ) )
# Reverse from 0 to mi
lowerCAmelCase : str = arr[mi::-1] + arr[mi + 1 : len(SCREAMING_SNAKE_CASE )]
# Reverse whole list
lowerCAmelCase : str = arr[cur - 1 :: -1] + arr[cur : len(SCREAMING_SNAKE_CASE )]
cur -= 1
return arr
if __name__ == "__main__":
lowerCAmelCase__ = input('''Enter numbers separated by a comma:\n''').strip()
lowerCAmelCase__ = [int(item) for item in user_input.split(''',''')]
print(pancake_sort(unsorted))
| 681 | 1 |
'''simple docstring'''
import gc
import tempfile
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device
snake_case_ = False
class a__ ( unittest.TestCase ):
pass
@nightly
@require_torch_gpu
class a__ ( unittest.TestCase ):
def lowercase__ (self : List[str] ) -> Dict:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowercase__ (self : Optional[Any] ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''', torch_dtype=torch.floataa )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
SCREAMING_SNAKE_CASE : List[str] = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' )
SCREAMING_SNAKE_CASE : Any = torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Any = pipe.dual_guided(
prompt='''first prompt''', image=__UpperCAmelCase, text_to_image_strength=0.75, generator=__UpperCAmelCase, guidance_scale=7.5, num_inference_steps=2, output_type='''numpy''', ).images
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Any = VersatileDiffusionPipeline.from_pretrained(__UpperCAmelCase, torch_dtype=torch.floataa )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Dict = generator.manual_seed(0 )
SCREAMING_SNAKE_CASE : str = pipe.dual_guided(
prompt='''first prompt''', image=__UpperCAmelCase, text_to_image_strength=0.75, generator=__UpperCAmelCase, guidance_scale=7.5, num_inference_steps=2, output_type='''numpy''', ).images
assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass"
def lowercase__ (self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''', torch_dtype=torch.floataa )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
SCREAMING_SNAKE_CASE : int = '''cyberpunk 2077'''
SCREAMING_SNAKE_CASE : List[str] = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' )
SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : List[Any] = pipe.dual_guided(
prompt=__UpperCAmelCase, image=__UpperCAmelCase, text_to_image_strength=0.75, generator=__UpperCAmelCase, guidance_scale=7.5, num_inference_steps=50, output_type='''numpy''', ).images
SCREAMING_SNAKE_CASE : str = image[0, 253:256, 253:256, -1]
assert image.shape == (1, 512, 512, 3)
SCREAMING_SNAKE_CASE : Dict = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
SCREAMING_SNAKE_CASE : Optional[int] = '''A painting of a squirrel eating a burger '''
SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Dict = pipe.text_to_image(
prompt=__UpperCAmelCase, generator=__UpperCAmelCase, guidance_scale=7.5, num_inference_steps=50, output_type='''numpy''' ).images
SCREAMING_SNAKE_CASE : Optional[Any] = image[0, 253:256, 253:256, -1]
assert image.shape == (1, 512, 512, 3)
SCREAMING_SNAKE_CASE : List[Any] = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
SCREAMING_SNAKE_CASE : Optional[Any] = pipe.image_variation(__UpperCAmelCase, generator=__UpperCAmelCase, output_type='''numpy''' ).images
SCREAMING_SNAKE_CASE : List[Any] = image[0, 253:256, 253:256, -1]
assert image.shape == (1, 512, 512, 3)
SCREAMING_SNAKE_CASE : List[Any] = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
| 507 |
'''simple docstring'''
from itertools import zip_longest
import requests
from bsa import BeautifulSoup
from pandas import DataFrame
def __lowercase (_SCREAMING_SNAKE_CASE :str = "laptop" ):
SCREAMING_SNAKE_CASE : str = F'''https://www.amazon.in/laptop/s?k={product}'''
SCREAMING_SNAKE_CASE : int = {
'''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36
(KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''',
'''Accept-Language''': '''en-US, en;q=0.5''',
}
SCREAMING_SNAKE_CASE : Dict = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).text )
# Initialize a Pandas dataframe with the column titles
SCREAMING_SNAKE_CASE : str = DataFrame(
columns=[
'''Product Title''',
'''Product Link''',
'''Current Price of the product''',
'''Product Rating''',
'''MRP of the product''',
'''Discount''',
] )
# Loop through each entry and store them in the dataframe
for item, _ in zip_longest(
soup.find_all(
'''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''} ) , ):
try:
SCREAMING_SNAKE_CASE : Optional[int] = item.ha.text
SCREAMING_SNAKE_CASE : Tuple = '''https://www.amazon.in/''' + item.ha.a['''href''']
SCREAMING_SNAKE_CASE : Any = item.find('''span''' , attrs={'''class''': '''a-offscreen'''} ).text
try:
SCREAMING_SNAKE_CASE : Optional[int] = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''} ).text
except AttributeError:
SCREAMING_SNAKE_CASE : Any = '''Not available'''
try:
SCREAMING_SNAKE_CASE : Union[str, Any] = (
'''₹'''
+ item.find(
'''span''' , attrs={'''class''': '''a-price a-text-price'''} ).text.split('''₹''' )[1]
)
except AttributeError:
SCREAMING_SNAKE_CASE : List[str] = ''''''
try:
SCREAMING_SNAKE_CASE : Optional[Any] = float(
(
(
float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) )
- float(product_price.strip('''₹''' ).replace(''',''' , '''''' ) )
)
/ float(product_mrp.strip('''₹''' ).replace(''',''' , '''''' ) )
)
* 1_00 )
except ValueError:
SCREAMING_SNAKE_CASE : Optional[Any] = float('''nan''' )
except AttributeError:
pass
SCREAMING_SNAKE_CASE : int = [
product_title,
product_link,
product_price,
product_rating,
product_mrp,
discount,
]
SCREAMING_SNAKE_CASE : int = ''' '''
SCREAMING_SNAKE_CASE : List[str] = ''' '''
data_frame.index += 1
return data_frame
if __name__ == "__main__":
snake_case_ = """headphones"""
get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
| 507 | 1 |
"""simple docstring"""
from math import acos, sin
from typing import List, Tuple, Union
import numpy as np
import torch
from PIL import Image
from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel
class __a ( lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE__ : List[str] = ["vqvae"]
def __init__( self , a__ , a__ , a__ , a__ , ):
super().__init__()
self.register_modules(unet=a__ , scheduler=a__ , mel=a__ , vqvae=a__ )
def snake_case_ ( self ):
return 50 if isinstance(self.scheduler , a__ ) else 10_00
@torch.no_grad()
def __call__( self , a__ = 1 , a__ = None , a__ = None , a__ = 0 , a__ = 0 , a__ = None , a__ = None , a__ = 0 , a__ = 0 , a__ = None , a__ = 0 , a__ = None , a__ = None , a__=True , ):
_lowerCamelCase = steps or self.get_default_steps()
self.scheduler.set_timesteps(a__ )
_lowerCamelCase = step_generator or generator
# For backwards compatibility
if type(self.unet.config.sample_size ) == int:
_lowerCamelCase = (self.unet.config.sample_size, self.unet.config.sample_size)
if noise is None:
_lowerCamelCase = randn_tensor(
(
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size[0],
self.unet.config.sample_size[1],
) , generator=a__ , device=self.device , )
_lowerCamelCase = noise
_lowerCamelCase = None
if audio_file is not None or raw_audio is not None:
self.mel.load_audio(a__ , a__ )
_lowerCamelCase = self.mel.audio_slice_to_image(a__ )
_lowerCamelCase = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape(
(input_image.height, input_image.width) )
_lowerCamelCase = (input_image / 2_55) * 2 - 1
_lowerCamelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device )
if self.vqvae is not None:
_lowerCamelCase = self.vqvae.encode(torch.unsqueeze(a__ , 0 ) ).latent_dist.sample(
generator=a__ )[0]
_lowerCamelCase = self.vqvae.config.scaling_factor * input_images
if start_step > 0:
_lowerCamelCase = self.scheduler.add_noise(a__ , a__ , self.scheduler.timesteps[start_step - 1] )
_lowerCamelCase = (
self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
)
_lowerCamelCase = int(mask_start_secs * pixels_per_second )
_lowerCamelCase = int(mask_end_secs * pixels_per_second )
_lowerCamelCase = self.scheduler.add_noise(a__ , a__ , torch.tensor(self.scheduler.timesteps[start_step:] ) )
for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ):
if isinstance(self.unet , a__ ):
_lowerCamelCase = self.unet(a__ , a__ , a__ )['sample']
else:
_lowerCamelCase = self.unet(a__ , a__ )['sample']
if isinstance(self.scheduler , a__ ):
_lowerCamelCase = self.scheduler.step(
model_output=a__ , timestep=a__ , sample=a__ , eta=a__ , generator=a__ , )['prev_sample']
else:
_lowerCamelCase = self.scheduler.step(
model_output=a__ , timestep=a__ , sample=a__ , generator=a__ , )['prev_sample']
if mask is not None:
if mask_start > 0:
_lowerCamelCase = mask[:, step, :, :mask_start]
if mask_end > 0:
_lowerCamelCase = mask[:, step, :, -mask_end:]
if self.vqvae is not None:
# 0.18215 was scaling factor used in training to ensure unit variance
_lowerCamelCase = 1 / self.vqvae.config.scaling_factor * images
_lowerCamelCase = self.vqvae.decode(a__ )['sample']
_lowerCamelCase = (images / 2 + 0.5).clamp(0 , 1 )
_lowerCamelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy()
_lowerCamelCase = (images * 2_55).round().astype('uint8' )
_lowerCamelCase = list(
(Image.fromarray(_[:, :, 0] ) for _ in images)
if images.shape[3] == 1
else (Image.fromarray(a__ , mode='RGB' ).convert('L' ) for _ in images) )
_lowerCamelCase = [self.mel.image_to_audio(a__ ) for _ in images]
if not return_dict:
return images, (self.mel.get_sample_rate(), audios)
return BaseOutput(**AudioPipelineOutput(np.array(a__ )[:, np.newaxis, :] ) , **ImagePipelineOutput(a__ ) )
@torch.no_grad()
def snake_case_ ( self , a__ , a__ = 50 ):
assert isinstance(self.scheduler , a__ )
self.scheduler.set_timesteps(a__ )
_lowerCamelCase = np.array(
[np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] )
_lowerCamelCase = (sample / 2_55) * 2 - 1
_lowerCamelCase = torch.Tensor(a__ ).to(self.device )
for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ):
_lowerCamelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
_lowerCamelCase = self.scheduler.alphas_cumprod[t]
_lowerCamelCase = (
self.scheduler.alphas_cumprod[prev_timestep]
if prev_timestep >= 0
else self.scheduler.final_alpha_cumprod
)
_lowerCamelCase = 1 - alpha_prod_t
_lowerCamelCase = self.unet(a__ , a__ )['sample']
_lowerCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output
_lowerCamelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
_lowerCamelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output
return sample
@staticmethod
def snake_case_ ( a__ , a__ , a__ ):
_lowerCamelCase = acos(torch.dot(torch.flatten(a__ ) , torch.flatten(a__ ) ) / torch.norm(a__ ) / torch.norm(a__ ) )
return sin((1 - alpha) * theta ) * xa / sin(a__ ) + sin(alpha * theta ) * xa / sin(a__ )
| 222 |
"""simple docstring"""
import json
from typing import TYPE_CHECKING, List, Optional, Tuple
from tokenizers import pre_tokenizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
A_ : int =logging.get_logger(__name__)
A_ : Union[str, Any] ={"""tokenizer_file""": """tokenizer.json"""}
A_ : Dict ={
"""tokenizer_file""": {
"""bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""",
"""bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""",
"""bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""",
"""bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""",
"""bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""",
"""bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""",
"""bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""",
},
}
class __a ( lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE__ : Dict = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE__ : Any = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE__ : Optional[Any] = ["input_ids", "attention_mask"]
SCREAMING_SNAKE_CASE__ : Optional[Any] = None
def __init__( self , a__=None , a__=None , a__=None , a__="<unk>" , a__="<s>" , a__="</s>" , a__="<pad>" , a__=False , a__=False , **a__ , ):
super().__init__(
a__ , a__ , tokenizer_file=a__ , unk_token=a__ , bos_token=a__ , eos_token=a__ , pad_token=a__ , add_prefix_space=a__ , clean_up_tokenization_spaces=a__ , **a__ , )
_lowerCamelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('add_prefix_space' , a__ ) != add_prefix_space:
_lowerCamelCase = getattr(a__ , pre_tok_state.pop('type' ) )
_lowerCamelCase = add_prefix_space
_lowerCamelCase = pre_tok_class(**a__ )
_lowerCamelCase = add_prefix_space
def snake_case_ ( self , *a__ , **a__ ):
_lowerCamelCase = kwargs.get('is_split_into_words' , a__ )
if not (self.add_prefix_space or not is_split_into_words):
raise Exception(
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 snake_case_ ( self , *a__ , **a__ ):
_lowerCamelCase = kwargs.get('is_split_into_words' , a__ )
if not (self.add_prefix_space or not is_split_into_words):
raise Exception(
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 snake_case_ ( self , a__ , a__ = None ):
_lowerCamelCase = self._tokenizer.model.save(a__ , name=a__ )
return tuple(a__ )
def snake_case_ ( self , a__ ):
_lowerCamelCase = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(a__ , add_special_tokens=a__ ) + [self.eos_token_id] )
if len(a__ ) > self.model_max_length:
_lowerCamelCase = input_ids[-self.model_max_length :]
return input_ids
| 222 | 1 |
'''simple docstring'''
from math import asin, atan, cos, radians, sin, sqrt, tan
lowerCAmelCase_ : Any = 6_378_137.0
lowerCAmelCase_ : List[str] = 6_356_752.314_245
lowerCAmelCase_ : Any = 6_37_81_37
def _lowerCamelCase ( lowercase : float , lowercase : float , lowercase : float , lowercase : float ) -> float:
_a = (AXIS_A - AXIS_B) / AXIS_A
_a = atan((1 - flattening) * tan(radians(lowercase ) ) )
_a = atan((1 - flattening) * tan(radians(lowercase ) ) )
_a = radians(lowercase )
_a = radians(lowercase )
# Equation
_a = sin((phi_a - phi_a) / 2 )
_a = sin((lambda_a - lambda_a) / 2 )
# Square both values
sin_sq_phi *= sin_sq_phi
sin_sq_lambda *= sin_sq_lambda
_a = sqrt(sin_sq_phi + (cos(lowercase ) * cos(lowercase ) * sin_sq_lambda) )
return 2 * RADIUS * asin(lowercase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 692 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowerCAmelCase_ : Any = {
'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'],
'tokenization_biogpt': ['BioGptTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ : List[str] = [
'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
lowerCAmelCase_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 692 | 1 |
from collections import defaultdict
def __UpperCamelCase ( _A : str , _A : str ) ->bool:
"""simple docstring"""
lowerCamelCase_ =first_str.lower().strip()
lowerCamelCase_ =second_str.lower().strip()
# Remove whitespace
lowerCamelCase_ =first_str.replace(""" """ , """""" )
lowerCamelCase_ =second_str.replace(""" """ , """""" )
# Strings of different lengths are not anagrams
if len(_A ) != len(_A ):
return False
# Default values for count should be 0
lowerCamelCase_ =defaultdict(_A )
# For each character in input strings,
# increment count in the corresponding
for i in range(len(_A ) ):
count[first_str[i]] += 1
count[second_str[i]] -= 1
return all(_count == 0 for _count in count.values() )
if __name__ == "__main__":
from doctest import testmod
testmod()
__A : Optional[int] = input('Enter the first string ').strip()
__A : str = input('Enter the second string ').strip()
__A : Union[str, Any] = check_anagrams(input_a, input_b)
print(F"""{input_a} and {input_b} are {"" if status else "not "}anagrams.""")
| 701 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
__A : int = {
'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json',
'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json',
'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json',
'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json',
'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json',
'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json',
'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json',
'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json',
}
class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__):
_UpperCamelCase:Any = "albert"
def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]:
super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
lowerCamelCase_ =vocab_size
lowerCamelCase_ =embedding_size
lowerCamelCase_ =hidden_size
lowerCamelCase_ =num_hidden_layers
lowerCamelCase_ =num_hidden_groups
lowerCamelCase_ =num_attention_heads
lowerCamelCase_ =inner_group_num
lowerCamelCase_ =hidden_act
lowerCamelCase_ =intermediate_size
lowerCamelCase_ =hidden_dropout_prob
lowerCamelCase_ =attention_probs_dropout_prob
lowerCamelCase_ =max_position_embeddings
lowerCamelCase_ =type_vocab_size
lowerCamelCase_ =initializer_range
lowerCamelCase_ =layer_norm_eps
lowerCamelCase_ =classifier_dropout_prob
lowerCamelCase_ =position_embedding_type
class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__):
@property
def _snake_case ( self )-> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""}
else:
lowerCamelCase_ ={0: """batch""", 1: """sequence"""}
return OrderedDict(
[
("""input_ids""", dynamic_axis),
("""attention_mask""", dynamic_axis),
("""token_type_ids""", dynamic_axis),
] )
| 75 | 0 |
from collections.abc import Callable
def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase : float = a
_lowerCAmelCase : float = b
if function(_lowerCamelCase ) == 0: # one of the a or b is a root for the function
return a
elif function(_lowerCamelCase ) == 0:
return b
elif (
function(_lowerCamelCase ) * function(_lowerCamelCase ) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval." )
else:
_lowerCAmelCase : float = start + (end - start) / 2.0
while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7
if function(_lowerCamelCase ) == 0:
return mid
elif function(_lowerCamelCase ) * function(_lowerCamelCase ) < 0:
_lowerCAmelCase : Any = mid
else:
_lowerCAmelCase : Optional[int] = mid
_lowerCAmelCase : List[str] = start + (end - start) / 2.0
return mid
def A ( _lowerCamelCase ):
'''simple docstring'''
return x**3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| 500 |
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
_snake_case = logging.get_logger(__name__)
def A ( _lowerCamelCase , _lowerCamelCase=False ):
'''simple docstring'''
_lowerCAmelCase : str = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((F"blocks.{i}.norm1.weight", F"deit.encoder.layer.{i}.layernorm_before.weight") )
rename_keys.append((F"blocks.{i}.norm1.bias", F"deit.encoder.layer.{i}.layernorm_before.bias") )
rename_keys.append((F"blocks.{i}.attn.proj.weight", F"deit.encoder.layer.{i}.attention.output.dense.weight") )
rename_keys.append((F"blocks.{i}.attn.proj.bias", F"deit.encoder.layer.{i}.attention.output.dense.bias") )
rename_keys.append((F"blocks.{i}.norm2.weight", F"deit.encoder.layer.{i}.layernorm_after.weight") )
rename_keys.append((F"blocks.{i}.norm2.bias", F"deit.encoder.layer.{i}.layernorm_after.bias") )
rename_keys.append((F"blocks.{i}.mlp.fc1.weight", F"deit.encoder.layer.{i}.intermediate.dense.weight") )
rename_keys.append((F"blocks.{i}.mlp.fc1.bias", F"deit.encoder.layer.{i}.intermediate.dense.bias") )
rename_keys.append((F"blocks.{i}.mlp.fc2.weight", F"deit.encoder.layer.{i}.output.dense.weight") )
rename_keys.append((F"blocks.{i}.mlp.fc2.bias", F"deit.encoder.layer.{i}.output.dense.bias") )
# projection layer + position embeddings
rename_keys.extend(
[
("cls_token", "deit.embeddings.cls_token"),
("dist_token", "deit.embeddings.distillation_token"),
("patch_embed.proj.weight", "deit.embeddings.patch_embeddings.projection.weight"),
("patch_embed.proj.bias", "deit.embeddings.patch_embeddings.projection.bias"),
("pos_embed", "deit.embeddings.position_embeddings"),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
("norm.weight", "layernorm.weight"),
("norm.bias", "layernorm.bias"),
("pre_logits.fc.weight", "pooler.dense.weight"),
("pre_logits.fc.bias", "pooler.dense.bias"),
] )
# if just the base model, we should remove "deit" from all keys that start with "deit"
_lowerCAmelCase : Any = [(pair[0], pair[1][4:]) if pair[1].startswith("deit" ) else pair for pair in rename_keys]
else:
# layernorm + classification heads
rename_keys.extend(
[
("norm.weight", "deit.layernorm.weight"),
("norm.bias", "deit.layernorm.bias"),
("head.weight", "cls_classifier.weight"),
("head.bias", "cls_classifier.bias"),
("head_dist.weight", "distillation_classifier.weight"),
("head_dist.bias", "distillation_classifier.bias"),
] )
return rename_keys
def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=False ):
'''simple docstring'''
for i in range(config.num_hidden_layers ):
if base_model:
_lowerCAmelCase : str = ""
else:
_lowerCAmelCase : Optional[int] = "deit."
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_lowerCAmelCase : List[Any] = state_dict.pop(F"blocks.{i}.attn.qkv.weight" )
_lowerCAmelCase : Union[str, Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" )
# next, add query, keys and values (in that order) to the state dict
_lowerCAmelCase : Any = in_proj_weight[
: config.hidden_size, :
]
_lowerCAmelCase : Tuple = in_proj_bias[: config.hidden_size]
_lowerCAmelCase : Any = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_lowerCAmelCase : int = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_lowerCAmelCase : Optional[int] = in_proj_weight[
-config.hidden_size :, :
]
_lowerCAmelCase : Dict = in_proj_bias[-config.hidden_size :]
def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase : Union[str, Any] = dct.pop(_lowerCamelCase )
_lowerCAmelCase : str = val
def A ( ):
'''simple docstring'''
_lowerCAmelCase : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg"
_lowerCAmelCase : List[Any] = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw )
return im
@torch.no_grad()
def A ( _lowerCamelCase , _lowerCamelCase ):
'''simple docstring'''
_lowerCAmelCase : Optional[int] = DeiTConfig()
# all deit models have fine-tuned heads
_lowerCAmelCase : Dict = False
# dataset (fine-tuned on ImageNet 2012), patch_size and image_size
_lowerCAmelCase : Optional[int] = 1_000
_lowerCAmelCase : Optional[Any] = "huggingface/label-files"
_lowerCAmelCase : Tuple = "imagenet-1k-id2label.json"
_lowerCAmelCase : Optional[int] = json.load(open(hf_hub_download(_lowerCamelCase , _lowerCamelCase , repo_type="dataset" ) , "r" ) )
_lowerCAmelCase : str = {int(_lowerCamelCase ): v for k, v in idalabel.items()}
_lowerCAmelCase : Union[str, Any] = idalabel
_lowerCAmelCase : Tuple = {v: k for k, v in idalabel.items()}
_lowerCAmelCase : Dict = int(deit_name[-6:-4] )
_lowerCAmelCase : Any = int(deit_name[-3:] )
# size of the architecture
if deit_name[9:].startswith("tiny" ):
_lowerCAmelCase : List[str] = 192
_lowerCAmelCase : int = 768
_lowerCAmelCase : int = 12
_lowerCAmelCase : Any = 3
elif deit_name[9:].startswith("small" ):
_lowerCAmelCase : int = 384
_lowerCAmelCase : Tuple = 1_536
_lowerCAmelCase : Dict = 12
_lowerCAmelCase : Any = 6
if deit_name[9:].startswith("base" ):
pass
elif deit_name[4:].startswith("large" ):
_lowerCAmelCase : List[str] = 1_024
_lowerCAmelCase : Tuple = 4_096
_lowerCAmelCase : Optional[Any] = 24
_lowerCAmelCase : str = 16
# load original model from timm
_lowerCAmelCase : Any = timm.create_model(_lowerCamelCase , pretrained=_lowerCamelCase )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_lowerCAmelCase : Optional[Any] = timm_model.state_dict()
_lowerCAmelCase : Optional[int] = create_rename_keys(_lowerCamelCase , _lowerCamelCase )
for src, dest in rename_keys:
rename_key(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
read_in_q_k_v(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
# load HuggingFace model
_lowerCAmelCase : Any = DeiTForImageClassificationWithTeacher(_lowerCamelCase ).eval()
model.load_state_dict(_lowerCamelCase )
# Check outputs on an image, prepared by DeiTImageProcessor
_lowerCAmelCase : Optional[int] = int(
(256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103
_lowerCAmelCase : Any = DeiTImageProcessor(size=_lowerCamelCase , crop_size=config.image_size )
_lowerCAmelCase : str = image_processor(images=prepare_img() , return_tensors="pt" )
_lowerCAmelCase : int = encoding["pixel_values"]
_lowerCAmelCase : int = model(_lowerCamelCase )
_lowerCAmelCase : Tuple = timm_model(_lowerCamelCase )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(_lowerCamelCase , outputs.logits , atol=1e-3 )
Path(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase )
print(F"Saving model {deit_name} to {pytorch_dump_folder_path}" )
model.save_pretrained(_lowerCamelCase )
print(F"Saving image processor to {pytorch_dump_folder_path}" )
image_processor.save_pretrained(_lowerCamelCase )
if __name__ == "__main__":
_snake_case = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--deit_name",
default="vit_deit_base_distilled_patch16_224",
type=str,
help="Name of the DeiT timm model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
)
_snake_case = parser.parse_args()
convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
| 500 | 1 |
def _A ( __magic_name__ , __magic_name__ ):
lowercase__ = len(__magic_name__ )
lowercase__ = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )]
# for each arr value, a sum of zero(0) can be formed by not taking any element
# hence True/1
for i in range(arr_len + 1 ):
lowercase__ = True
# sum is not zero and set is empty then false
for i in range(1 , required_sum + 1 ):
lowercase__ = False
for i in range(1 , arr_len + 1 ):
for j in range(1 , required_sum + 1 ):
if arr[i - 1] > j:
lowercase__ = subset[i - 1][j]
if arr[i - 1] <= j:
lowercase__ = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]]
return subset[arr_len][required_sum]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 611 |
import collections
import inspect
import unittest
from typing import Dict, List, Tuple
from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MaskFormerSwinBackbone
from transformers.models.maskformer import MaskFormerSwinModel
class lowerCAmelCase :
def __init__( self :Union[str, Any] , _lowercase :Dict , _lowercase :int=13 , _lowercase :Dict=32 , _lowercase :List[Any]=2 , _lowercase :Any=3 , _lowercase :Optional[Any]=16 , _lowercase :str=[1, 2, 1] , _lowercase :Tuple=[2, 2, 4] , _lowercase :int=2 , _lowercase :Optional[Any]=2.0 , _lowercase :List[Any]=True , _lowercase :Tuple=0.0 , _lowercase :List[str]=0.0 , _lowercase :List[str]=0.1 , _lowercase :Optional[int]="gelu" , _lowercase :Dict=False , _lowercase :Union[str, Any]=True , _lowercase :str=0.02 , _lowercase :str=1e-5 , _lowercase :Optional[Any]=True , _lowercase :Any=None , _lowercase :int=True , _lowercase :Any=10 , _lowercase :Optional[int]=8 , _lowercase :List[str]=["stage1", "stage2", "stage3"] , _lowercase :int=[1, 2, 3] , ):
'''simple docstring'''
lowercase__ = parent
lowercase__ = batch_size
lowercase__ = image_size
lowercase__ = patch_size
lowercase__ = num_channels
lowercase__ = embed_dim
lowercase__ = depths
lowercase__ = num_heads
lowercase__ = window_size
lowercase__ = mlp_ratio
lowercase__ = qkv_bias
lowercase__ = hidden_dropout_prob
lowercase__ = attention_probs_dropout_prob
lowercase__ = drop_path_rate
lowercase__ = hidden_act
lowercase__ = use_absolute_embeddings
lowercase__ = patch_norm
lowercase__ = layer_norm_eps
lowercase__ = initializer_range
lowercase__ = is_training
lowercase__ = scope
lowercase__ = use_labels
lowercase__ = type_sequence_label_size
lowercase__ = encoder_stride
lowercase__ = out_features
lowercase__ = out_indices
def UpperCAmelCase ( self :int ):
'''simple docstring'''
lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase__ = None
if self.use_labels:
lowercase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowercase__ = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
return MaskFormerSwinConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , )
def UpperCAmelCase ( self :Any , _lowercase :List[Any] , _lowercase :List[str] , _lowercase :Optional[Any] ):
'''simple docstring'''
lowercase__ = MaskFormerSwinModel(config=_lowercase )
model.to(_lowercase )
model.eval()
lowercase__ = model(_lowercase )
lowercase__ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
lowercase__ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) )
def UpperCAmelCase ( self :Tuple , _lowercase :int , _lowercase :Union[str, Any] , _lowercase :Any ):
'''simple docstring'''
lowercase__ = MaskFormerSwinBackbone(config=_lowercase )
model.to(_lowercase )
model.eval()
lowercase__ = model(_lowercase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] )
# verify channels
self.parent.assertEqual(len(model.channels ) , len(config.out_features ) )
self.parent.assertListEqual(model.channels , [16, 32, 64] )
# verify ValueError
with self.parent.assertRaises(_lowercase ):
lowercase__ = ["stem"]
lowercase__ = MaskFormerSwinBackbone(config=_lowercase )
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
lowercase__ = self.prepare_config_and_inputs()
lowercase__ , lowercase__ , lowercase__ = config_and_inputs
lowercase__ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class lowerCAmelCase ( lowercase_ , lowercase_ , unittest.TestCase ):
__lowerCamelCase = (
(
MaskFormerSwinModel,
MaskFormerSwinBackbone,
)
if is_torch_available()
else ()
)
__lowerCamelCase = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
def UpperCAmelCase ( self :Dict ):
'''simple docstring'''
lowercase__ = MaskFormerSwinModelTester(self )
lowercase__ = ConfigTester(self , config_class=_lowercase , embed_dim=37 )
@require_torch_multi_gpu
@unittest.skip(
reason=(
"`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"
" `nn.DataParallel`"
) )
def UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
pass
def UpperCAmelCase ( self :Optional[int] ):
'''simple docstring'''
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def UpperCAmelCase ( self :str ):
'''simple docstring'''
return
def UpperCAmelCase ( self :Any ):
'''simple docstring'''
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowercase )
def UpperCAmelCase ( self :Tuple ):
'''simple docstring'''
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*_lowercase )
@unittest.skip("Swin does not use inputs_embeds" )
def UpperCAmelCase ( self :List[str] ):
'''simple docstring'''
pass
@unittest.skip("Swin does not support feedforward chunking" )
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
pass
def UpperCAmelCase ( self :List[str] ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = model_class(_lowercase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
lowercase__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_lowercase , nn.Linear ) )
def UpperCAmelCase ( self :Dict ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = model_class(_lowercase )
lowercase__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase__ = [*signature.parameters.keys()]
lowercase__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowercase )
@unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions" )
def UpperCAmelCase ( self :Union[str, Any] ):
'''simple docstring'''
pass
@unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" )
def UpperCAmelCase ( self :List[Any] ):
'''simple docstring'''
pass
def UpperCAmelCase ( self :int , _lowercase :List[Any] , _lowercase :Dict , _lowercase :str , _lowercase :str ):
'''simple docstring'''
lowercase__ = model_class(_lowercase )
model.to(_lowercase )
model.eval()
with torch.no_grad():
lowercase__ = model(**self._prepare_for_class(_lowercase , _lowercase ) )
lowercase__ = outputs.hidden_states
lowercase__ = getattr(
self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(_lowercase ) , _lowercase )
# Swin has a different seq_length
lowercase__ = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowercase__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def UpperCAmelCase ( self :str ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
lowercase__ = True
self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , _lowercase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase__ = True
self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , _lowercase )
def UpperCAmelCase ( self :Optional[int] ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = 3
lowercase__ = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
lowercase__ = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowercase__ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
lowercase__ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
lowercase__ = True
self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase__ = True
self.check_hidden_states_output(_lowercase , _lowercase , _lowercase , (padded_height, padded_width) )
@unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints" )
def UpperCAmelCase ( self :Dict ):
'''simple docstring'''
pass
@unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" )
def UpperCAmelCase ( self :Optional[Any] ):
'''simple docstring'''
pass
@unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" )
def UpperCAmelCase ( self :Optional[Any] ):
'''simple docstring'''
pass
def UpperCAmelCase ( self :Dict ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
def set_nan_tensor_to_zero(_lowercase :Optional[Any] ):
lowercase__ = 0
return t
def check_equivalence(_lowercase :Optional[int] , _lowercase :List[str] , _lowercase :Optional[Any] , _lowercase :str={} ):
with torch.no_grad():
lowercase__ = model(**_lowercase , return_dict=_lowercase , **_lowercase )
lowercase__ = model(**_lowercase , return_dict=_lowercase , **_lowercase ).to_tuple()
def recursive_check(_lowercase :int , _lowercase :Dict ):
if isinstance(_lowercase , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(_lowercase , _lowercase ):
recursive_check(_lowercase , _lowercase )
elif isinstance(_lowercase , _lowercase ):
for tuple_iterable_value, dict_iterable_value in zip(
tuple_object.values() , dict_object.values() ):
recursive_check(_lowercase , _lowercase )
elif tuple_object is None:
return
else:
self.assertTrue(
torch.allclose(
set_nan_tensor_to_zero(_lowercase ) , set_nan_tensor_to_zero(_lowercase ) , atol=1e-5 ) , msg=(
"Tuple and dict output are not equal. Difference:"
f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:'''
f''' {torch.isnan(_lowercase ).any()} and `inf`: {torch.isinf(_lowercase )}. Dict has'''
f''' `nan`: {torch.isnan(_lowercase ).any()} and `inf`: {torch.isinf(_lowercase )}.'''
) , )
recursive_check(_lowercase , _lowercase )
for model_class in self.all_model_classes:
lowercase__ = model_class(_lowercase )
model.to(_lowercase )
model.eval()
lowercase__ = self._prepare_for_class(_lowercase , _lowercase )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase )
check_equivalence(_lowercase , _lowercase , _lowercase )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase )
check_equivalence(_lowercase , _lowercase , _lowercase )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase )
check_equivalence(_lowercase , _lowercase , _lowercase , {"output_hidden_states": True} )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase )
lowercase__ = self._prepare_for_class(_lowercase , _lowercase , return_labels=_lowercase )
check_equivalence(_lowercase , _lowercase , _lowercase , {"output_hidden_states": True} )
@require_torch
class lowerCAmelCase ( unittest.TestCase , lowercase_ ):
__lowerCamelCase = (MaskFormerSwinBackbone,) if is_torch_available() else ()
__lowerCamelCase = MaskFormerSwinConfig
def UpperCAmelCase ( self :Dict ):
'''simple docstring'''
lowercase__ = MaskFormerSwinModelTester(self )
def UpperCAmelCase ( self :str ):
'''simple docstring'''
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = inputs_dict["pixel_values"].shape[0]
for backbone_class in self.all_model_classes:
lowercase__ = backbone_class(_lowercase )
backbone.to(_lowercase )
backbone.eval()
lowercase__ = backbone(**_lowercase )
# Test default outputs and verify feature maps
self.assertIsInstance(outputs.feature_maps , _lowercase )
self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) )
for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ):
self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) )
self.assertIsNone(outputs.hidden_states )
self.assertIsNone(outputs.attentions )
# Test output_hidden_states=True
lowercase__ = backbone(**_lowercase , output_hidden_states=_lowercase )
self.assertIsNotNone(outputs.hidden_states )
self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) )
# We skip the stem layer
for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ):
for hidden_state in hidden_states:
# Hidden states are in the format (batch_size, (height * width), n_channels)
lowercase__ , lowercase__ , lowercase__ = hidden_state.shape
self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) )
# Test output_attentions=True
if self.has_attentions:
lowercase__ = backbone(**_lowercase , output_attentions=_lowercase )
self.assertIsNotNone(outputs.attentions )
| 611 | 1 |
"""simple docstring"""
from typing import Any
class __magic_name__ :
'''simple docstring'''
def __init__( self , _a ):
"""simple docstring"""
lowerCamelCase = data
lowerCamelCase = None
def __repr__( self ):
"""simple docstring"""
return f'Node({self.data})'
class __magic_name__ :
'''simple docstring'''
def __init__( self ):
"""simple docstring"""
lowerCamelCase = None
def __iter__( self ):
"""simple docstring"""
lowerCamelCase = self.head
while node:
yield node.data
lowerCamelCase = node.next
def __len__( self ):
"""simple docstring"""
return sum(1 for _ in self )
def __repr__( self ):
"""simple docstring"""
return "->".join([str(_UpperCamelCase ) for item in self] )
def __getitem__( self , _a ):
"""simple docstring"""
if not 0 <= index < len(self ):
raise ValueError("""list index out of range.""" )
for i, node in enumerate(self ):
if i == index:
return node
return None
def __setitem__( self , _a , _a ):
"""simple docstring"""
if not 0 <= index < len(self ):
raise ValueError("""list index out of range.""" )
lowerCamelCase = self.head
for _ in range(_UpperCamelCase ):
lowerCamelCase = current.next
lowerCamelCase = data
def _lowerCAmelCase ( self , _a ):
"""simple docstring"""
self.insert_nth(len(self ) , _UpperCamelCase )
def _lowerCAmelCase ( self , _a ):
"""simple docstring"""
self.insert_nth(0 , _UpperCamelCase )
def _lowerCAmelCase ( self , _a , _a ):
"""simple docstring"""
if not 0 <= index <= len(self ):
raise IndexError("""list index out of range""" )
lowerCamelCase = Node(_UpperCamelCase )
if self.head is None:
lowerCamelCase = new_node
elif index == 0:
lowerCamelCase = self.head # link new_node to head
lowerCamelCase = new_node
else:
lowerCamelCase = self.head
for _ in range(index - 1 ):
lowerCamelCase = temp.next
lowerCamelCase = temp.next
lowerCamelCase = new_node
def _lowerCAmelCase ( self ): # print every node data
"""simple docstring"""
print(self )
def _lowerCAmelCase ( self ):
"""simple docstring"""
return self.delete_nth(0 )
def _lowerCAmelCase ( self ): # delete from tail
"""simple docstring"""
return self.delete_nth(len(self ) - 1 )
def _lowerCAmelCase ( self , _a = 0 ):
"""simple docstring"""
if not 0 <= index <= len(self ) - 1: # test if index is valid
raise IndexError("""List index out of range.""" )
lowerCamelCase = self.head # default first node
if index == 0:
lowerCamelCase = self.head.next
else:
lowerCamelCase = self.head
for _ in range(index - 1 ):
lowerCamelCase = temp.next
lowerCamelCase = temp.next
lowerCamelCase = temp.next.next
return delete_node.data
def _lowerCAmelCase ( self ):
"""simple docstring"""
return self.head is None
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = None
lowerCamelCase = self.head
while current:
# Store the current node's next node.
lowerCamelCase = current.next
# Make the current node's next point backwards
lowerCamelCase = prev
# Make the previous node be the current node
lowerCamelCase = current
# Make the current node the next node (to progress iteration)
lowerCamelCase = next_node
# Return prev in order to put the head at the end
lowerCamelCase = prev
def a__ ( ) -> None:
lowerCamelCase = LinkedList()
assert linked_list.is_empty() is True
assert str(__UpperCamelCase ) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10 ):
assert len(__UpperCamelCase ) == i
linked_list.insert_nth(__UpperCamelCase , i + 1 )
assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(1 , 11 ) )
linked_list.insert_head(0 )
linked_list.insert_tail(11 )
assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(0 , 12 ) )
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9 ) == 10
assert linked_list.delete_tail() == 11
assert len(__UpperCamelCase ) == 9
assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(1 , 10 ) )
assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True
for i in range(0 , 9 ):
lowerCamelCase = -i
assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True
linked_list.reverse()
assert str(__UpperCamelCase ) == "->".join(str(__UpperCamelCase ) for i in range(-8 , 1 ) )
def a__ ( ) -> None:
lowerCamelCase = [
-9,
1_00,
Node(77_34_51_12 ),
"""dlrow olleH""",
7,
55_55,
0,
-1_92.5_55_55,
"""Hello, world!""",
77.9,
Node(10 ),
None,
None,
12.20,
]
lowerCamelCase = LinkedList()
for i in test_input:
linked_list.insert_tail(__UpperCamelCase )
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(__UpperCamelCase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
lowerCamelCase = linked_list.delete_head()
assert result == -9
assert (
str(__UpperCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
lowerCamelCase = linked_list.delete_tail()
assert result == 12.2
assert (
str(__UpperCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
lowerCamelCase = linked_list.delete_nth(10 )
assert result is None
assert (
str(__UpperCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node("""Hello again, world!""" ) )
assert (
str(__UpperCamelCase )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(__UpperCamelCase )
assert (
str(__UpperCamelCase )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(__UpperCamelCase )
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def a__ ( ) -> Dict:
from doctest import testmod
testmod()
lowerCamelCase = LinkedList()
linked_list.insert_head(input("""Inserting 1st at head """ ).strip() )
linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() )
print("""\nPrint list:""" )
linked_list.print_list()
linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() )
linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() )
print("""\nPrint list:""" )
linked_list.print_list()
print("""\nDelete head""" )
linked_list.delete_head()
print("""Delete tail""" )
linked_list.delete_tail()
print("""\nPrint list:""" )
linked_list.print_list()
print("""\nReverse linked list""" )
linked_list.reverse()
print("""\nPrint list:""" )
linked_list.print_list()
print("""\nString representation of linked list:""" )
print(__UpperCamelCase )
print("""\nReading/changing Node data using indexing:""" )
print(F'Element at Position 1: {linked_list[1]}' )
lowerCamelCase = input("""Enter New Value: """ ).strip()
print("""New list:""" )
print(__UpperCamelCase )
print(F'length of linked_list is : {len(__UpperCamelCase )}' )
if __name__ == "__main__":
main()
| 543 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps
from ..pipeline_params import (
IMAGE_TO_IMAGE_IMAGE_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class lowerCAmelCase_ ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ):
__UpperCAmelCase =CycleDiffusionPipeline
__UpperCAmelCase =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
'negative_prompt',
'height',
'width',
'negative_prompt_embeds',
}
__UpperCAmelCase =PipelineTesterMixin.required_optional_params - {'latents'}
__UpperCAmelCase =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'source_prompt'} )
__UpperCAmelCase =IMAGE_TO_IMAGE_IMAGE_PARAMS
__UpperCAmelCase =IMAGE_TO_IMAGE_IMAGE_PARAMS
def UpperCamelCase ( self )-> 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 , )
_A = DDIMScheduler(
beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' , num_train_timesteps=1000 , clip_sample=_UpperCamelCase , set_alpha_to_one=_UpperCamelCase , )
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 , )
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=1000 , )
_A = CLIPTextModel(_UpperCamelCase )
_A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
_A = {
'unet': unet,
'scheduler': scheduler,
'vae': vae,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'safety_checker': None,
'feature_extractor': None,
}
return components
def UpperCamelCase ( self , _UpperCamelCase , _UpperCamelCase=0 )-> List[Any]:
_A = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCamelCase ) ).to(_UpperCamelCase )
_A = image / 2 + 0.5
if str(_UpperCamelCase ).startswith('mps' ):
_A = torch.manual_seed(_UpperCamelCase )
else:
_A = torch.Generator(device=_UpperCamelCase ).manual_seed(_UpperCamelCase )
_A = {
'prompt': 'An astronaut riding an elephant',
'source_prompt': 'An astronaut riding a horse',
'image': image,
'generator': generator,
'num_inference_steps': 2,
'eta': 0.1,
'strength': 0.8,
'guidance_scale': 3,
'source_guidance_scale': 1,
'output_type': 'numpy',
}
return inputs
def UpperCamelCase ( self )-> Any:
_A = 'cpu' # ensure determinism for the device-dependent torch.Generator
_A = self.get_dummy_components()
_A = CycleDiffusionPipeline(**_UpperCamelCase )
_A = pipe.to(_UpperCamelCase )
pipe.set_progress_bar_config(disable=_UpperCamelCase )
_A = self.get_dummy_inputs(_UpperCamelCase )
_A = pipe(**_UpperCamelCase )
_A = output.images
_A = images[0, -3:, -3:, -1]
assert images.shape == (1, 32, 32, 3)
_A = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' )
def UpperCamelCase ( self )-> List[Any]:
_A = self.get_dummy_components()
for name, module in components.items():
if hasattr(_UpperCamelCase , 'half' ):
_A = module.half()
_A = CycleDiffusionPipeline(**_UpperCamelCase )
_A = pipe.to(_UpperCamelCase )
pipe.set_progress_bar_config(disable=_UpperCamelCase )
_A = self.get_dummy_inputs(_UpperCamelCase )
_A = pipe(**_UpperCamelCase )
_A = output.images
_A = images[0, -3:, -3:, -1]
assert images.shape == (1, 32, 32, 3)
_A = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def UpperCamelCase ( self )-> Any:
return super().test_save_load_local()
@unittest.skip('non-deterministic pipeline' )
def UpperCamelCase ( self )-> List[Any]:
return super().test_inference_batch_single_identical()
@skip_mps
def UpperCamelCase ( self )-> int:
return super().test_dict_tuple_outputs_equivalent()
@skip_mps
def UpperCamelCase ( self )-> Tuple:
return super().test_save_load_optional_components()
@skip_mps
def UpperCamelCase ( self )-> Optional[Any]:
return super().test_attention_slicing_forward_pass()
@slow
@require_torch_gpu
class lowerCAmelCase_ ( unittest.TestCase ):
def UpperCamelCase ( self )-> Any:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase ( self )-> int:
_A = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/cycle-diffusion/black_colored_car.png' )
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy' )
_A = init_image.resize((512, 512) )
_A = 'CompVis/stable-diffusion-v1-4'
_A = DDIMScheduler.from_pretrained(_UpperCamelCase , subfolder='scheduler' )
_A = CycleDiffusionPipeline.from_pretrained(
_UpperCamelCase , scheduler=_UpperCamelCase , safety_checker=_UpperCamelCase , torch_dtype=torch.floataa , revision='fp16' )
pipe.to(_UpperCamelCase )
pipe.set_progress_bar_config(disable=_UpperCamelCase )
pipe.enable_attention_slicing()
_A = 'A black colored car'
_A = 'A blue colored car'
_A = torch.manual_seed(0 )
_A = pipe(
prompt=_UpperCamelCase , source_prompt=_UpperCamelCase , image=_UpperCamelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_UpperCamelCase , output_type='np' , )
_A = output.images
# the values aren't exactly equal, but the images look the same visually
assert np.abs(image - expected_image ).max() < 5e-1
def UpperCamelCase ( self )-> Union[str, Any]:
_A = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/cycle-diffusion/black_colored_car.png' )
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy' )
_A = init_image.resize((512, 512) )
_A = 'CompVis/stable-diffusion-v1-4'
_A = DDIMScheduler.from_pretrained(_UpperCamelCase , subfolder='scheduler' )
_A = CycleDiffusionPipeline.from_pretrained(_UpperCamelCase , scheduler=_UpperCamelCase , safety_checker=_UpperCamelCase )
pipe.to(_UpperCamelCase )
pipe.set_progress_bar_config(disable=_UpperCamelCase )
pipe.enable_attention_slicing()
_A = 'A black colored car'
_A = 'A blue colored car'
_A = torch.manual_seed(0 )
_A = pipe(
prompt=_UpperCamelCase , source_prompt=_UpperCamelCase , image=_UpperCamelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_UpperCamelCase , output_type='np' , )
_A = output.images
assert np.abs(image - expected_image ).max() < 2e-2
| 292 | 0 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block
@dataclass
class UpperCAmelCase ( __snake_case ):
a: torch.FloatTensor
class UpperCAmelCase ( __snake_case , __snake_case ):
@register_to_config
def __init__( self: str , __UpperCamelCase: int = 6_5536 , __UpperCamelCase: Optional[int] = None , __UpperCamelCase: int = 2 , __UpperCamelCase: int = 2 , __UpperCamelCase: int = 0 , __UpperCamelCase: str = "fourier" , __UpperCamelCase: bool = True , __UpperCamelCase: bool = False , __UpperCamelCase: float = 0.0 , __UpperCamelCase: Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , __UpperCamelCase: Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , __UpperCamelCase: Tuple[str] = "UNetMidBlock1D" , __UpperCamelCase: str = None , __UpperCamelCase: Tuple[int] = (32, 32, 64) , __UpperCamelCase: str = None , __UpperCamelCase: int = 8 , __UpperCamelCase: int = 1 , __UpperCamelCase: bool = False , ):
super().__init__()
_a = sample_size
# time
if time_embedding_type == "fourier":
_a = GaussianFourierProjection(
embedding_size=8 , set_W_to_weight=__UpperCamelCase , log=__UpperCamelCase , flip_sin_to_cos=__UpperCamelCase )
_a = 2 * block_out_channels[0]
elif time_embedding_type == "positional":
_a = Timesteps(
block_out_channels[0] , flip_sin_to_cos=__UpperCamelCase , downscale_freq_shift=__UpperCamelCase )
_a = block_out_channels[0]
if use_timestep_embedding:
_a = block_out_channels[0] * 4
_a = TimestepEmbedding(
in_channels=__UpperCamelCase , time_embed_dim=__UpperCamelCase , act_fn=__UpperCamelCase , out_dim=block_out_channels[0] , )
_a = nn.ModuleList([] )
_a = None
_a = nn.ModuleList([] )
_a = None
# down
_a = in_channels
for i, down_block_type in enumerate(__UpperCamelCase ):
_a = output_channel
_a = block_out_channels[i]
if i == 0:
input_channel += extra_in_channels
_a = i == len(__UpperCamelCase ) - 1
_a = get_down_block(
__UpperCamelCase , num_layers=__UpperCamelCase , in_channels=__UpperCamelCase , out_channels=__UpperCamelCase , temb_channels=block_out_channels[0] , add_downsample=not is_final_block or downsample_each_block , )
self.down_blocks.append(__UpperCamelCase )
# mid
_a = get_mid_block(
__UpperCamelCase , in_channels=block_out_channels[-1] , mid_channels=block_out_channels[-1] , out_channels=block_out_channels[-1] , embed_dim=block_out_channels[0] , num_layers=__UpperCamelCase , add_downsample=__UpperCamelCase , )
# up
_a = list(reversed(__UpperCamelCase ) )
_a = reversed_block_out_channels[0]
if out_block_type is None:
_a = out_channels
else:
_a = block_out_channels[0]
for i, up_block_type in enumerate(__UpperCamelCase ):
_a = output_channel
_a = (
reversed_block_out_channels[i + 1] if i < len(__UpperCamelCase ) - 1 else final_upsample_channels
)
_a = i == len(__UpperCamelCase ) - 1
_a = get_up_block(
__UpperCamelCase , num_layers=__UpperCamelCase , in_channels=__UpperCamelCase , out_channels=__UpperCamelCase , temb_channels=block_out_channels[0] , add_upsample=not is_final_block , )
self.up_blocks.append(__UpperCamelCase )
_a = output_channel
# out
_a = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 , 32 )
_a = get_out_block(
out_block_type=__UpperCamelCase , num_groups_out=__UpperCamelCase , embed_dim=block_out_channels[0] , out_channels=__UpperCamelCase , act_fn=__UpperCamelCase , fc_dim=block_out_channels[-1] // 4 , )
def _A ( self: List[Any] , __UpperCamelCase: torch.FloatTensor , __UpperCamelCase: Union[torch.Tensor, float, int] , __UpperCamelCase: bool = True , ):
_a = timestep
if not torch.is_tensor(__UpperCamelCase ):
_a = torch.tensor([timesteps] , dtype=torch.long , device=sample.device )
elif torch.is_tensor(__UpperCamelCase ) and len(timesteps.shape ) == 0:
_a = timesteps[None].to(sample.device )
_a = self.time_proj(__UpperCamelCase )
if self.config.use_timestep_embedding:
_a = self.time_mlp(__UpperCamelCase )
else:
_a = timestep_embed[..., None]
_a = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype )
_a = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) )
# 2. down
_a = ()
for downsample_block in self.down_blocks:
_a , _a = downsample_block(hidden_states=__UpperCamelCase , temb=__UpperCamelCase )
down_block_res_samples += res_samples
# 3. mid
if self.mid_block:
_a = self.mid_block(__UpperCamelCase , __UpperCamelCase )
# 4. up
for i, upsample_block in enumerate(self.up_blocks ):
_a = down_block_res_samples[-1:]
_a = down_block_res_samples[:-1]
_a = upsample_block(__UpperCamelCase , res_hidden_states_tuple=__UpperCamelCase , temb=__UpperCamelCase )
# 5. post-process
if self.out_block:
_a = self.out_block(__UpperCamelCase , __UpperCamelCase )
if not return_dict:
return (sample,)
return UNetaDOutput(sample=__UpperCamelCase )
| 705 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowerCamelCase :List[Any] = {
'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'],
'tokenization_roc_bert': ['RoCBertTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
pass
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase :str = [
'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'RoCBertForCausalLM',
'RoCBertForMaskedLM',
'RoCBertForMultipleChoice',
'RoCBertForPreTraining',
'RoCBertForQuestionAnswering',
'RoCBertForSequenceClassification',
'RoCBertForTokenClassification',
'RoCBertLayer',
'RoCBertModel',
'RoCBertPreTrainedModel',
'load_tf_weights_in_roc_bert',
]
if TYPE_CHECKING:
from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
from .tokenization_roc_bert import RoCBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
raise OptionalDependencyNotAvailable()
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roc_bert import (
ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RoCBertForCausalLM,
RoCBertForMaskedLM,
RoCBertForMultipleChoice,
RoCBertForPreTraining,
RoCBertForQuestionAnswering,
RoCBertForSequenceClassification,
RoCBertForTokenClassification,
RoCBertLayer,
RoCBertModel,
RoCBertPreTrainedModel,
load_tf_weights_in_roc_bert,
)
else:
import sys
lowerCamelCase :int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 346 | 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
a_ :Dict = {
'Acehnese Arabic': 'ace_Arab',
'Acehnese Latin': 'ace_Latn',
'Mesopotamian Arabic': 'acm_Arab',
'Ta\'izzi-Adeni Arabic': 'acq_Arab',
'Tunisian Arabic': 'aeb_Arab',
'Afrikaans': 'afr_Latn',
'South Levantine Arabic': 'ajp_Arab',
'Akan': 'aka_Latn',
'Amharic': 'amh_Ethi',
'North Levantine Arabic': 'apc_Arab',
'Modern Standard Arabic': 'arb_Arab',
'Modern Standard Arabic Romanized': 'arb_Latn',
'Najdi Arabic': 'ars_Arab',
'Moroccan Arabic': 'ary_Arab',
'Egyptian Arabic': 'arz_Arab',
'Assamese': 'asm_Beng',
'Asturian': 'ast_Latn',
'Awadhi': 'awa_Deva',
'Central Aymara': 'ayr_Latn',
'South Azerbaijani': 'azb_Arab',
'North Azerbaijani': 'azj_Latn',
'Bashkir': 'bak_Cyrl',
'Bambara': 'bam_Latn',
'Balinese': 'ban_Latn',
'Belarusian': 'bel_Cyrl',
'Bemba': 'bem_Latn',
'Bengali': 'ben_Beng',
'Bhojpuri': 'bho_Deva',
'Banjar Arabic': 'bjn_Arab',
'Banjar Latin': 'bjn_Latn',
'Standard Tibetan': 'bod_Tibt',
'Bosnian': 'bos_Latn',
'Buginese': 'bug_Latn',
'Bulgarian': 'bul_Cyrl',
'Catalan': 'cat_Latn',
'Cebuano': 'ceb_Latn',
'Czech': 'ces_Latn',
'Chokwe': 'cjk_Latn',
'Central Kurdish': 'ckb_Arab',
'Crimean Tatar': 'crh_Latn',
'Welsh': 'cym_Latn',
'Danish': 'dan_Latn',
'German': 'deu_Latn',
'Southwestern Dinka': 'dik_Latn',
'Dyula': 'dyu_Latn',
'Dzongkha': 'dzo_Tibt',
'Greek': 'ell_Grek',
'English': 'eng_Latn',
'Esperanto': 'epo_Latn',
'Estonian': 'est_Latn',
'Basque': 'eus_Latn',
'Ewe': 'ewe_Latn',
'Faroese': 'fao_Latn',
'Fijian': 'fij_Latn',
'Finnish': 'fin_Latn',
'Fon': 'fon_Latn',
'French': 'fra_Latn',
'Friulian': 'fur_Latn',
'Nigerian Fulfulde': 'fuv_Latn',
'Scottish Gaelic': 'gla_Latn',
'Irish': 'gle_Latn',
'Galician': 'glg_Latn',
'Guarani': 'grn_Latn',
'Gujarati': 'guj_Gujr',
'Haitian Creole': 'hat_Latn',
'Hausa': 'hau_Latn',
'Hebrew': 'heb_Hebr',
'Hindi': 'hin_Deva',
'Chhattisgarhi': 'hne_Deva',
'Croatian': 'hrv_Latn',
'Hungarian': 'hun_Latn',
'Armenian': 'hye_Armn',
'Igbo': 'ibo_Latn',
'Ilocano': 'ilo_Latn',
'Indonesian': 'ind_Latn',
'Icelandic': 'isl_Latn',
'Italian': 'ita_Latn',
'Javanese': 'jav_Latn',
'Japanese': 'jpn_Jpan',
'Kabyle': 'kab_Latn',
'Jingpho': 'kac_Latn',
'Kamba': 'kam_Latn',
'Kannada': 'kan_Knda',
'Kashmiri Arabic': 'kas_Arab',
'Kashmiri Devanagari': 'kas_Deva',
'Georgian': 'kat_Geor',
'Central Kanuri Arabic': 'knc_Arab',
'Central Kanuri Latin': 'knc_Latn',
'Kazakh': 'kaz_Cyrl',
'Kabiyè': 'kbp_Latn',
'Kabuverdianu': 'kea_Latn',
'Khmer': 'khm_Khmr',
'Kikuyu': 'kik_Latn',
'Kinyarwanda': 'kin_Latn',
'Kyrgyz': 'kir_Cyrl',
'Kimbundu': 'kmb_Latn',
'Northern Kurdish': 'kmr_Latn',
'Kikongo': 'kon_Latn',
'Korean': 'kor_Hang',
'Lao': 'lao_Laoo',
'Ligurian': 'lij_Latn',
'Limburgish': 'lim_Latn',
'Lingala': 'lin_Latn',
'Lithuanian': 'lit_Latn',
'Lombard': 'lmo_Latn',
'Latgalian': 'ltg_Latn',
'Luxembourgish': 'ltz_Latn',
'Luba-Kasai': 'lua_Latn',
'Ganda': 'lug_Latn',
'Luo': 'luo_Latn',
'Mizo': 'lus_Latn',
'Standard Latvian': 'lvs_Latn',
'Magahi': 'mag_Deva',
'Maithili': 'mai_Deva',
'Malayalam': 'mal_Mlym',
'Marathi': 'mar_Deva',
'Minangkabau Arabic ': 'min_Arab',
'Minangkabau Latin': 'min_Latn',
'Macedonian': 'mkd_Cyrl',
'Plateau Malagasy': 'plt_Latn',
'Maltese': 'mlt_Latn',
'Meitei Bengali': 'mni_Beng',
'Halh Mongolian': 'khk_Cyrl',
'Mossi': 'mos_Latn',
'Maori': 'mri_Latn',
'Burmese': 'mya_Mymr',
'Dutch': 'nld_Latn',
'Norwegian Nynorsk': 'nno_Latn',
'Norwegian Bokmål': 'nob_Latn',
'Nepali': 'npi_Deva',
'Northern Sotho': 'nso_Latn',
'Nuer': 'nus_Latn',
'Nyanja': 'nya_Latn',
'Occitan': 'oci_Latn',
'West Central Oromo': 'gaz_Latn',
'Odia': 'ory_Orya',
'Pangasinan': 'pag_Latn',
'Eastern Panjabi': 'pan_Guru',
'Papiamento': 'pap_Latn',
'Western Persian': 'pes_Arab',
'Polish': 'pol_Latn',
'Portuguese': 'por_Latn',
'Dari': 'prs_Arab',
'Southern Pashto': 'pbt_Arab',
'Ayacucho Quechua': 'quy_Latn',
'Romanian': 'ron_Latn',
'Rundi': 'run_Latn',
'Russian': 'rus_Cyrl',
'Sango': 'sag_Latn',
'Sanskrit': 'san_Deva',
'Santali': 'sat_Olck',
'Sicilian': 'scn_Latn',
'Shan': 'shn_Mymr',
'Sinhala': 'sin_Sinh',
'Slovak': 'slk_Latn',
'Slovenian': 'slv_Latn',
'Samoan': 'smo_Latn',
'Shona': 'sna_Latn',
'Sindhi': 'snd_Arab',
'Somali': 'som_Latn',
'Southern Sotho': 'sot_Latn',
'Spanish': 'spa_Latn',
'Tosk Albanian': 'als_Latn',
'Sardinian': 'srd_Latn',
'Serbian': 'srp_Cyrl',
'Swati': 'ssw_Latn',
'Sundanese': 'sun_Latn',
'Swedish': 'swe_Latn',
'Swahili': 'swh_Latn',
'Silesian': 'szl_Latn',
'Tamil': 'tam_Taml',
'Tatar': 'tat_Cyrl',
'Telugu': 'tel_Telu',
'Tajik': 'tgk_Cyrl',
'Tagalog': 'tgl_Latn',
'Thai': 'tha_Thai',
'Tigrinya': 'tir_Ethi',
'Tamasheq Latin': 'taq_Latn',
'Tamasheq Tifinagh': 'taq_Tfng',
'Tok Pisin': 'tpi_Latn',
'Tswana': 'tsn_Latn',
'Tsonga': 'tso_Latn',
'Turkmen': 'tuk_Latn',
'Tumbuka': 'tum_Latn',
'Turkish': 'tur_Latn',
'Twi': 'twi_Latn',
'Central Atlas Tamazight': 'tzm_Tfng',
'Uyghur': 'uig_Arab',
'Ukrainian': 'ukr_Cyrl',
'Umbundu': 'umb_Latn',
'Urdu': 'urd_Arab',
'Northern Uzbek': 'uzn_Latn',
'Venetian': 'vec_Latn',
'Vietnamese': 'vie_Latn',
'Waray': 'war_Latn',
'Wolof': 'wol_Latn',
'Xhosa': 'xho_Latn',
'Eastern Yiddish': 'ydd_Hebr',
'Yoruba': 'yor_Latn',
'Yue Chinese': 'yue_Hant',
'Chinese Simplified': 'zho_Hans',
'Chinese Traditional': 'zho_Hant',
'Standard Malay': 'zsm_Latn',
'Zulu': 'zul_Latn',
}
class lowercase ( _UpperCAmelCase ):
lowerCamelCase : str = '''facebook/nllb-200-distilled-600M'''
lowerCamelCase : Optional[int] = (
'''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should '''
'''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, '''
'''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in '''
'''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.'''
)
lowerCamelCase : int = '''translator'''
lowerCamelCase : List[Any] = AutoTokenizer
lowerCamelCase : Dict = AutoModelForSeqaSeqLM
lowerCamelCase : Union[str, Any] = LANGUAGE_CODES
lowerCamelCase : Optional[int] = ['''text''', '''text''', '''text''']
lowerCamelCase : Union[str, Any] = ['''text''']
def lowercase__ ( self : Any , _lowercase : Any , _lowercase : List[str] , _lowercase : Optional[Any] ):
if src_lang not in self.lang_to_code:
raise ValueError(f"""{src_lang} is not a supported language.""" )
if tgt_lang not in self.lang_to_code:
raise ValueError(f"""{tgt_lang} is not a supported language.""" )
SCREAMING_SNAKE_CASE__ : int = self.lang_to_code[src_lang]
SCREAMING_SNAKE_CASE__ : List[str] = self.lang_to_code[tgt_lang]
return self.pre_processor._build_translation_inputs(
_lowercase , return_tensors='''pt''' , src_lang=_lowercase , tgt_lang=_lowercase )
def lowercase__ ( self : Tuple , _lowercase : List[Any] ):
return self.model.generate(**_lowercase )
def lowercase__ ( self : Optional[int] , _lowercase : int ):
return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=_lowercase )
| 35 | from argparse import ArgumentParser
from datasets.commands.convert import ConvertCommand
from datasets.commands.dummy_data import DummyDataCommand
from datasets.commands.env import EnvironmentCommand
from datasets.commands.run_beam import RunBeamCommand
from datasets.commands.test import TestCommand
from datasets.utils.logging import set_verbosity_info
def __lowerCAmelCase ( A_ : Optional[int] ) -> Optional[int]:
return {key.lstrip("-" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )}
def __lowerCAmelCase ( ) -> Dict:
__UpperCAmelCase = ArgumentParser(
"HuggingFace Datasets CLI tool" , usage="datasets-cli <command> [<args>]" , allow_abbrev=A_ )
__UpperCAmelCase = parser.add_subparsers(help="datasets-cli command helpers" )
set_verbosity_info()
# Register commands
ConvertCommand.register_subcommand(A_ )
EnvironmentCommand.register_subcommand(A_ )
TestCommand.register_subcommand(A_ )
RunBeamCommand.register_subcommand(A_ )
DummyDataCommand.register_subcommand(A_ )
# Parse args
__UpperCAmelCase , __UpperCAmelCase = parser.parse_known_args()
if not hasattr(A_ , "func" ):
parser.print_help()
exit(1 )
__UpperCAmelCase = parse_unknown_args(A_ )
# Run
__UpperCAmelCase = args.func(A_ , **A_ )
service.run()
if __name__ == "__main__":
main()
| 221 | 0 |
'''simple docstring'''
from __future__ import annotations
A : str = 8.988e9 # units = N * m^s * C^-2
def lowercase_ ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) ->dict[str, float]:
_snake_case: Union[str, Any] = abs(chargea * chargea )
if (force, chargea, chargea, distance).count(0 ) != 1:
raise ValueError('One and only one argument must be 0' )
if distance < 0:
raise ValueError('Distance cannot be negative' )
if force == 0:
_snake_case: Union[str, Any] = COULOMBS_CONSTANT * charge_product / (distance**2)
return {"force": force}
elif chargea == 0:
_snake_case: Dict = abs(lowercase__ ) * (distance**2) / (COULOMBS_CONSTANT * chargea)
return {"charge1": chargea}
elif chargea == 0:
_snake_case: Dict = abs(lowercase__ ) * (distance**2) / (COULOMBS_CONSTANT * chargea)
return {"charge2": chargea}
elif distance == 0:
_snake_case: Dict = (COULOMBS_CONSTANT * charge_product / abs(lowercase__ )) ** 0.5
return {"distance": distance}
raise ValueError('Exactly one argument must be 0' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 710 |
'''simple docstring'''
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_tensorflow_text_available():
from transformers.models.bert import TFBertTokenizer
A : Tuple = ['bert-base-uncased', 'bert-base-cased']
A : str = 'hf-internal-testing/tiny-bert-tf-only'
if is_tf_available():
class lowerCamelCase ( tf.keras.Model ):
def __init__( self : Union[str, Any] , __snake_case : List[Any] ):
'''simple docstring'''
super().__init__()
_snake_case: List[Any] = tokenizer
_snake_case: str = AutoConfig.from_pretrained(__snake_case )
_snake_case: List[Any] = TFAutoModel.from_config(__snake_case )
def SCREAMING_SNAKE_CASE_ ( self : str , __snake_case : List[str] ):
'''simple docstring'''
_snake_case: Optional[int] = self.tokenizer(__snake_case )
_snake_case: Tuple = self.bert(**__snake_case )
return out["pooler_output"]
@require_tf
@require_tensorflow_text
class lowerCamelCase ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self : Tuple ):
'''simple docstring'''
super().setUp()
_snake_case: List[Any] = [
BertTokenizer.from_pretrained(__snake_case ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
] # repeat for when fast_bert_tokenizer=false
_snake_case: List[Any] = [TFBertTokenizer.from_pretrained(__snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
TFBertTokenizer.from_pretrained(__snake_case , use_fast_bert_tokenizer=__snake_case )
for checkpoint in TOKENIZER_CHECKPOINTS
]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
_snake_case: int = [
'This is a straightforward English test sentence.',
'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.',
'Now we\'re going to add some Chinese: 一 二 三 一二三',
'And some much more rare Chinese: 齉 堃 齉堃',
'Je vais aussi écrire en français pour tester les accents',
'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ',
]
_snake_case: str = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ):
'''simple docstring'''
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in (self.test_sentences, self.paired_sentences):
_snake_case: List[Any] = tokenizer(__snake_case , return_tensors='tf' , padding='longest' )
_snake_case: Optional[Any] = tf_tokenizer(__snake_case )
for key in python_outputs.keys():
self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) )
self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self : int ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
_snake_case: str = tf_tokenizer(self.paired_sentences )
_snake_case: Any = tf_tokenizer(
text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , )
for key in merged_outputs.keys():
self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self : Tuple ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
_snake_case: List[str] = tf.function(__snake_case )
for test_inputs in (self.test_sentences, self.paired_sentences):
_snake_case: Union[str, Any] = tf.constant(__snake_case )
_snake_case: Any = compiled_tokenizer(__snake_case )
_snake_case: Union[str, Any] = tf_tokenizer(__snake_case )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self : List[str] ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
_snake_case: Optional[Any] = ModelToSave(tokenizer=__snake_case )
_snake_case: Tuple = tf.convert_to_tensor(self.test_sentences )
_snake_case: List[str] = model(__snake_case ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
_snake_case: List[str] = Path(__snake_case ) / 'saved.model'
model.save(__snake_case )
_snake_case: int = tf.keras.models.load_model(__snake_case )
_snake_case: int = loaded_model(__snake_case )
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
| 273 | 0 |
'''simple docstring'''
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
a__ : List[str] = 16
a__ : int = 32
def __snake_case ( SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : int = 16 ) -> int:
"""simple docstring"""
UpperCAmelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' )
UpperCAmelCase = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(SCREAMING_SNAKE_CASE_ : Union[str, Any] ):
# max_length=None => use the model max length (it's actually the default)
UpperCAmelCase = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
UpperCAmelCase = datasets.map(
SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
UpperCAmelCase = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(SCREAMING_SNAKE_CASE_ : str ):
# On TPU it's best to pad everything to the same length or training will be very slow.
UpperCAmelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
UpperCAmelCase = 16
elif accelerator.mixed_precision != "no":
UpperCAmelCase = 8
else:
UpperCAmelCase = None
return tokenizer.pad(
SCREAMING_SNAKE_CASE_ , padding='''longest''' , max_length=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
# Instantiate dataloaders.
UpperCAmelCase = DataLoader(
tokenized_datasets['''train'''] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = DataLoader(
tokenized_datasets['''validation'''] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
a__ : Optional[Any] = mocked_dataloaders # noqa: F811
def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any ) -> Any:
"""simple docstring"""
if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , SCREAMING_SNAKE_CASE_ ) == "1":
UpperCAmelCase = 2
# Initialize accelerator
UpperCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
UpperCAmelCase = config['''lr''']
UpperCAmelCase = int(config['''num_epochs'''] )
UpperCAmelCase = int(config['''seed'''] )
UpperCAmelCase = int(config['''batch_size'''] )
UpperCAmelCase = evaluate.load('''glue''' , '''mrpc''' )
# If the batch size is too big we use gradient accumulation
UpperCAmelCase = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
UpperCAmelCase = batch_size // MAX_GPU_BATCH_SIZE
UpperCAmelCase = MAX_GPU_BATCH_SIZE
set_seed(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase, UpperCAmelCase = get_dataloaders(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
UpperCAmelCase = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=SCREAMING_SNAKE_CASE_ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
UpperCAmelCase = model.to(accelerator.device )
# Instantiate optimizer
UpperCAmelCase = AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ )
# Instantiate scheduler
UpperCAmelCase = get_linear_schedule_with_warmup(
optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=100 , num_training_steps=(len(SCREAMING_SNAKE_CASE_ ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Now we train the model
for epoch in range(SCREAMING_SNAKE_CASE_ ):
model.train()
for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = outputs.loss
UpperCAmelCase = loss / gradient_accumulation_steps
accelerator.backward(SCREAMING_SNAKE_CASE_ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
UpperCAmelCase = 0
for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
UpperCAmelCase = model(**SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = outputs.logits.argmax(dim=-1 )
UpperCAmelCase, UpperCAmelCase = accelerator.gather((predictions, batch['''labels''']) )
# New Code #
# First we check if it's a distributed system
if accelerator.use_distributed:
# Then see if we're on the last batch of our eval dataloader
if step == len(SCREAMING_SNAKE_CASE_ ) - 1:
# Last batch needs to be truncated on distributed systems as it contains additional samples
UpperCAmelCase = predictions[: len(eval_dataloader.dataset ) - samples_seen]
UpperCAmelCase = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
# Otherwise we add the number of samples seen
samples_seen += references.shape[0]
# All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
# accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ , )
UpperCAmelCase = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"epoch {epoch}:" , SCREAMING_SNAKE_CASE_ )
def __snake_case ( ) -> Optional[int]:
"""simple docstring"""
UpperCAmelCase = argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''' , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' )
UpperCAmelCase = parser.parse_args()
UpperCAmelCase = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if __name__ == "__main__":
main()
| 51 |
'''simple docstring'''
import hashlib
import unittest
from typing import Dict
import numpy as np
from transformers import (
MODEL_FOR_MASK_GENERATION_MAPPING,
TF_MODEL_FOR_MASK_GENERATION_MAPPING,
is_vision_available,
pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
if is_vision_available():
from PIL import Image
else:
class lowerCAmelCase__ :
'''simple docstring'''
@staticmethod
def __snake_case ( *a__ : List[Any] , **a__ : Optional[int] ):
pass
def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> str:
"""simple docstring"""
UpperCAmelCase = hashlib.mda(image.tobytes() )
return m.hexdigest()[:10]
def __snake_case ( SCREAMING_SNAKE_CASE_ : Image ) -> Dict:
"""simple docstring"""
UpperCAmelCase = np.array(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase = npimg.shape
return {"hash": hashimage(SCREAMING_SNAKE_CASE_ ), "shape": shape}
@is_pipeline_test
@require_vision
@require_torch
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
_lowerCamelCase =dict(
(list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) )
_lowerCamelCase =dict(
(list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) )
def __snake_case ( self : Union[str, Any] , a__ : Optional[int] , a__ : Dict , a__ : int ):
UpperCAmelCase = MaskGenerationPipeline(model=a__ , image_processor=a__ )
return image_segmenter, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def __snake_case ( self : int , a__ : Dict , a__ : Tuple ):
pass
@require_tf
@unittest.skip('''Image segmentation not implemented in TF''' )
def __snake_case ( self : str ):
pass
@slow
@require_torch
def __snake_case ( self : Optional[Any] ):
UpperCAmelCase = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' )
UpperCAmelCase = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=256 )
# Shortening by hashing
UpperCAmelCase = []
for i, o in enumerate(outputs['''masks'''] ):
new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}]
# fmt: off
self.assertEqual(
nested_simplify(a__ , decimals=4 ) , [
{'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444},
{'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.021},
{'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167},
{'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132},
{'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053},
{'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_967},
{'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.993},
{'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_909},
{'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_879},
{'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_834},
{'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_716},
{'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_612},
{'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_599},
{'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_552},
{'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_532},
{'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_516},
{'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_499},
{'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_483},
{'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_464},
{'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.943},
{'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.943},
{'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_408},
{'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_335},
{'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_326},
{'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_262},
{'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_999},
{'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_986},
{'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_984},
{'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_873},
{'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_871}
] , )
# fmt: on
@require_torch
@slow
def __snake_case ( self : Dict ):
UpperCAmelCase = '''facebook/sam-vit-huge'''
UpperCAmelCase = pipeline('''mask-generation''' , model=a__ )
UpperCAmelCase = image_segmenter(
'''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=256 )
# Shortening by hashing
UpperCAmelCase = []
for i, o in enumerate(outputs['''masks'''] ):
new_outupt += [{"mask": mask_to_test_readable(a__ ), "scores": outputs["scores"][i]}]
self.assertEqual(
nested_simplify(a__ , decimals=4 ) , [
{'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_444},
{'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_210},
{'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_167},
{'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_132},
{'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_053},
] , )
| 51 | 1 |
from ..utils import DummyObject, requires_backends
class _SCREAMING_SNAKE_CASE ( metaclass=_lowerCAmelCase ):
a_ : Dict = ['''torch''', '''transformers''', '''onnx''']
def __init__(self , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(self , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
class _SCREAMING_SNAKE_CASE ( metaclass=_lowerCAmelCase ):
a_ : Dict = ['''torch''', '''transformers''', '''onnx''']
def __init__(self , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(self , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
class _SCREAMING_SNAKE_CASE ( metaclass=_lowerCAmelCase ):
a_ : List[Any] = ['''torch''', '''transformers''', '''onnx''']
def __init__(self , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(self , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
class _SCREAMING_SNAKE_CASE ( metaclass=_lowerCAmelCase ):
a_ : str = ['''torch''', '''transformers''', '''onnx''']
def __init__(self , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(self , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
class _SCREAMING_SNAKE_CASE ( metaclass=_lowerCAmelCase ):
a_ : List[str] = ['''torch''', '''transformers''', '''onnx''']
def __init__(self , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(self , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
class _SCREAMING_SNAKE_CASE ( metaclass=_lowerCAmelCase ):
a_ : List[Any] = ['''torch''', '''transformers''', '''onnx''']
def __init__(self , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(self , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
@classmethod
def A__ (cls , *UpperCAmelCase , **UpperCAmelCase):
'''simple docstring'''
requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''])
| 142 |
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import jax
import jaxlib
UpperCamelCase_ = get_logger()
UpperCamelCase_ = None
class _SCREAMING_SNAKE_CASE ( TensorFormatter[Mapping, '''jax.Array''', Mapping] ):
def __init__(self , UpperCAmelCase=None , UpperCAmelCase=None , **UpperCAmelCase):
'''simple docstring'''
super().__init__(features=UpperCAmelCase)
import jax
from jaxlib.xla_client import Device
if isinstance(UpperCAmelCase , UpperCAmelCase):
raise ValueError(
f"""Expected {device} to be a `str` not {type(UpperCAmelCase)}, as `jaxlib.xla_extension.Device` """
'''is not serializable neither with `pickle` nor with `dill`. Instead you can surround '''
'''the device with `str()` to get its string identifier that will be internally mapped '''
'''to the actual `jaxlib.xla_extension.Device`.''')
__UpperCAmelCase =device if isinstance(UpperCAmelCase , UpperCAmelCase) else str(jax.devices()[0])
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
__UpperCAmelCase =self._map_devices_to_str()
if self.device not in list(DEVICE_MAPPING.keys()):
logger.warning(
f"""Device with string identifier {self.device} not listed among the available """
f"""devices: {list(DEVICE_MAPPING.keys())}, so falling back to the default """
f"""device: {str(jax.devices()[0])}.""")
__UpperCAmelCase =str(jax.devices()[0])
__UpperCAmelCase =jnp_array_kwargs
@staticmethod
def A__ ():
'''simple docstring'''
import jax
return {str(UpperCAmelCase): device for device in jax.devices()}
def A__ (self , UpperCAmelCase):
'''simple docstring'''
import jax
import jax.numpy as jnp
if isinstance(UpperCAmelCase , UpperCAmelCase) and column:
if all(
isinstance(UpperCAmelCase , jax.Array) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column):
return jnp.stack(UpperCAmelCase , axis=0)
return column
def A__ (self , UpperCAmelCase):
'''simple docstring'''
import jax
import jax.numpy as jnp
if isinstance(UpperCAmelCase , (str, bytes, type(UpperCAmelCase))):
return value
elif isinstance(UpperCAmelCase , (np.character, np.ndarray)) and np.issubdtype(value.dtype , np.character):
return value.tolist()
__UpperCAmelCase ={}
if isinstance(UpperCAmelCase , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.integer):
# the default int precision depends on the jax config
# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
if jax.config.jax_enable_xaa:
__UpperCAmelCase ={'''dtype''': jnp.intaa}
else:
__UpperCAmelCase ={'''dtype''': jnp.intaa}
elif isinstance(UpperCAmelCase , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.floating):
__UpperCAmelCase ={'''dtype''': jnp.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(UpperCAmelCase , PIL.Image.Image):
__UpperCAmelCase =np.asarray(UpperCAmelCase)
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
__UpperCAmelCase =self._map_devices_to_str()
with jax.default_device(DEVICE_MAPPING[self.device]):
# calling jnp.array on a np.ndarray does copy the data
# see https://github.com/google/jax/issues/4486
return jnp.array(UpperCAmelCase , **{**default_dtype, **self.jnp_array_kwargs})
def A__ (self , UpperCAmelCase):
'''simple docstring'''
import jax
# support for torch, tf, jax etc.
if config.TORCH_AVAILABLE and "torch" in sys.modules:
import torch
if isinstance(UpperCAmelCase , torch.Tensor):
return self._tensorize(data_struct.detach().cpu().numpy()[()])
if hasattr(UpperCAmelCase , '''__array__''') and not isinstance(UpperCAmelCase , jax.Array):
__UpperCAmelCase =data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(UpperCAmelCase , np.ndarray):
if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(UpperCAmelCase) for substruct in data_struct])
elif isinstance(UpperCAmelCase , (list, tuple)):
return self._consolidate([self.recursive_tensorize(UpperCAmelCase) for substruct in data_struct])
return self._tensorize(UpperCAmelCase)
def A__ (self , UpperCAmelCase):
'''simple docstring'''
return map_nested(self._recursive_tensorize , UpperCAmelCase , map_list=UpperCAmelCase)
def A__ (self , UpperCAmelCase):
'''simple docstring'''
__UpperCAmelCase =self.numpy_arrow_extractor().extract_row(UpperCAmelCase)
__UpperCAmelCase =self.python_features_decoder.decode_row(UpperCAmelCase)
return self.recursive_tensorize(UpperCAmelCase)
def A__ (self , UpperCAmelCase):
'''simple docstring'''
__UpperCAmelCase =self.numpy_arrow_extractor().extract_column(UpperCAmelCase)
__UpperCAmelCase =self.python_features_decoder.decode_column(UpperCAmelCase , pa_table.column_names[0])
__UpperCAmelCase =self.recursive_tensorize(UpperCAmelCase)
__UpperCAmelCase =self._consolidate(UpperCAmelCase)
return column
def A__ (self , UpperCAmelCase):
'''simple docstring'''
__UpperCAmelCase =self.numpy_arrow_extractor().extract_batch(UpperCAmelCase)
__UpperCAmelCase =self.python_features_decoder.decode_batch(UpperCAmelCase)
__UpperCAmelCase =self.recursive_tensorize(UpperCAmelCase)
for column_name in batch:
__UpperCAmelCase =self._consolidate(batch[column_name])
return batch
| 142 | 1 |
'''simple docstring'''
import math
def UpperCAmelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : List[str]):
if 0 not in (x, y):
# We use the relation x^y = y*log10(x), where 10 is the base.
return y * math.logaa(__lowercase)
else:
if x == 0: # 0 raised to any number is 0
return 0
elif y == 0:
return 1 # any number raised to 0 is 1
raise AssertionError('This should never happen')
if __name__ == "__main__": # Main function
# Read two numbers from input and typecast them to int using map function.
# Here x is the base and y is the power.
A = '''Enter the base and the power separated by a comma: '''
A = map(int, input(prompt).split(','))
A = map(int, input(prompt).split(','))
# We find the log of each number, using the function res(), which takes two
# arguments.
A = res(xa, ya)
A = res(xa, ya)
# We check for the largest number
if resa > resa:
print('Largest number is', xa, '^', ya)
elif resa > resa:
print('Largest number is', xa, '^', ya)
else:
print('Both are equal')
| 320 |
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'''
_UpperCAmelCase : Union[str, Any] = LEDConfig
_UpperCAmelCase : int = {}
_UpperCAmelCase : List[str] = "gelu"
def __init__( self : Union[str, Any] , lowercase : Optional[int] , lowercase : Dict=13 , lowercase : Dict=7 , lowercase : Tuple=True , lowercase : Dict=False , lowercase : Dict=99 , lowercase : Any=32 , lowercase : List[Any]=2 , lowercase : List[str]=4 , lowercase : List[str]=37 , lowercase : Dict=0.1 , lowercase : int=0.1 , lowercase : List[Any]=20 , lowercase : int=2 , lowercase : Optional[Any]=1 , lowercase : List[str]=0 , lowercase : Optional[int]=4 , ):
'''simple docstring'''
_snake_case = parent
_snake_case = batch_size
_snake_case = seq_length
_snake_case = is_training
_snake_case = use_labels
_snake_case = vocab_size
_snake_case = hidden_size
_snake_case = num_hidden_layers
_snake_case = num_attention_heads
_snake_case = intermediate_size
_snake_case = hidden_dropout_prob
_snake_case = attention_probs_dropout_prob
_snake_case = max_position_embeddings
_snake_case = eos_token_id
_snake_case = pad_token_id
_snake_case = bos_token_id
_snake_case = 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
_snake_case = 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
_snake_case = (
self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window
)
def A ( self : List[Any] ):
'''simple docstring'''
_snake_case = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
_snake_case = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
_snake_case = tf.concat([input_ids, eos_tensor] , axis=1 )
_snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_snake_case = 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 , )
_snake_case = prepare_led_inputs_dict(lowercase , lowercase , lowercase )
_snake_case = tf.concat(
[tf.zeros_like(lowercase )[:, :-1], tf.ones_like(lowercase )[:, -1:]] , axis=-1 , )
_snake_case = global_attention_mask
return config, inputs_dict
def A ( self : str , lowercase : str , lowercase : Union[str, Any] ):
'''simple docstring'''
_snake_case = TFLEDModel(config=lowercase ).get_decoder()
_snake_case = inputs_dict['input_ids']
_snake_case = input_ids[:1, :]
_snake_case = inputs_dict['attention_mask'][:1, :]
_snake_case = 1
# first forward pass
_snake_case = model(lowercase , attention_mask=lowercase , use_cache=lowercase )
_snake_case , _snake_case = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
_snake_case = ids_tensor((self.batch_size, 3) , config.vocab_size )
_snake_case = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
_snake_case = tf.concat([input_ids, next_tokens] , axis=-1 )
_snake_case = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
_snake_case = model(lowercase , attention_mask=lowercase )[0]
_snake_case = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
_snake_case = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
_snake_case = output_from_no_past[:, -3:, random_slice_idx]
_snake_case = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(lowercase , lowercase , rtol=1E-3 )
def a_ ( __lowercase : List[Any] , __lowercase : Optional[Any] , __lowercase : Dict , __lowercase : List[str]=None , __lowercase : List[str]=None , __lowercase : List[str]=None , __lowercase : str=None , ) -> Union[str, Any]:
if attention_mask is None:
_snake_case = tf.cast(tf.math.not_equal(__lowercase , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
_snake_case = 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:
_snake_case = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_snake_case = 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__ ( UpperCAmelCase ,UpperCAmelCase ,unittest.TestCase ):
'''simple docstring'''
_UpperCAmelCase : Optional[Any] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else ()
_UpperCAmelCase : Optional[int] = (TFLEDForConditionalGeneration,) if is_tf_available() else ()
_UpperCAmelCase : Tuple = (
{
"conversational": TFLEDForConditionalGeneration,
"feature-extraction": TFLEDModel,
"summarization": TFLEDForConditionalGeneration,
"text2text-generation": TFLEDForConditionalGeneration,
"translation": TFLEDForConditionalGeneration,
}
if is_tf_available()
else {}
)
_UpperCAmelCase : str = True
_UpperCAmelCase : List[str] = False
_UpperCAmelCase : str = False
_UpperCAmelCase : List[Any] = False
def A ( self : Any ):
'''simple docstring'''
_snake_case = TFLEDModelTester(self )
_snake_case = ConfigTester(self , config_class=lowercase )
def A ( self : Union[str, Any] ):
'''simple docstring'''
self.config_tester.run_common_tests()
def A ( self : Union[str, Any] ):
'''simple docstring'''
_snake_case = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*lowercase )
def A ( self : Optional[Any] ):
'''simple docstring'''
_snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common()
_snake_case = tf.zeros_like(inputs_dict['attention_mask'] )
_snake_case = 2
_snake_case = tf.where(
tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['global_attention_mask'] , )
_snake_case = True
_snake_case = self.model_tester.seq_length
_snake_case = self.model_tester.encoder_seq_length
def check_decoder_attentions_output(lowercase : List[str] ):
_snake_case = outputs.decoder_attentions
self.assertEqual(len(lowercase ) , 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(lowercase : List[str] ):
_snake_case = [t.numpy() for t in outputs.encoder_attentions]
_snake_case = [t.numpy() for t in outputs.encoder_global_attentions]
self.assertEqual(len(lowercase ) , self.model_tester.num_hidden_layers )
self.assertEqual(len(lowercase ) , 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:
_snake_case = True
_snake_case = False
_snake_case = False
_snake_case = model_class(lowercase )
_snake_case = model(self._prepare_for_class(lowercase , lowercase ) )
_snake_case = len(lowercase )
self.assertEqual(config.output_hidden_states , lowercase )
check_encoder_attentions_output(lowercase )
if self.is_encoder_decoder:
_snake_case = model_class(lowercase )
_snake_case = model(self._prepare_for_class(lowercase , lowercase ) )
self.assertEqual(config.output_hidden_states , lowercase )
check_decoder_attentions_output(lowercase )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
_snake_case = True
_snake_case = model_class(lowercase )
_snake_case = model(self._prepare_for_class(lowercase , lowercase ) )
self.assertEqual(config.output_hidden_states , lowercase )
check_encoder_attentions_output(lowercase )
# Check attention is always last and order is fine
_snake_case = True
_snake_case = True
_snake_case = model_class(lowercase )
_snake_case = model(self._prepare_for_class(lowercase , lowercase ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(lowercase ) )
self.assertEqual(model.config.output_hidden_states , lowercase )
check_encoder_attentions_output(lowercase )
@unittest.skip('LED keeps using potentially symbolic tensors in conditionals and breaks tracing.' )
def A ( self : List[Any] ):
'''simple docstring'''
pass
def A ( self : Any ):
'''simple docstring'''
pass
def a_ ( __lowercase : str ) -> Optional[Any]:
return tf.constant(__lowercase , dtype=tf.intaa )
_lowerCamelCase : List[Any] = 1E-4
@slow
@require_tf
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
'''simple docstring'''
def A ( self : Optional[Any] ):
'''simple docstring'''
_snake_case = TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384' ).led
# change to intended input here
_snake_case = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] )
_snake_case = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] )
_snake_case = prepare_led_inputs_dict(model.config , lowercase , lowercase )
_snake_case = model(**lowercase )[0]
_snake_case = (1, 1_024, 768)
self.assertEqual(output.shape , lowercase )
# change to expected output here
_snake_case = tf.convert_to_tensor(
[[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , )
tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-3 )
def A ( self : str ):
'''simple docstring'''
_snake_case = TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384' )
# change to intended input here
_snake_case = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] )
_snake_case = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] )
_snake_case = prepare_led_inputs_dict(model.config , lowercase , lowercase )
_snake_case = model(**lowercase )[0]
_snake_case = (1, 1_024, model.config.vocab_size)
self.assertEqual(output.shape , lowercase )
# change to expected output here
_snake_case = tf.convert_to_tensor(
[[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , )
tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-3 , rtol=1E-3 ) | 686 | 0 |
def UpperCamelCase_( _A :int , _A :int )-> str:
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must be positive integers" )
UpperCamelCase__ = str(bin(_A ) )
binary_number += "0" * shift_amount
return binary_number
def UpperCamelCase_( _A :int , _A :int )-> str:
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must be positive integers" )
UpperCamelCase__ = str(bin(_A ) )[2:]
if shift_amount >= len(_A ):
return "0b0"
UpperCamelCase__ = binary_number[: len(_A ) - shift_amount]
return "0b" + shifted_binary_number
def UpperCamelCase_( _A :int , _A :int )-> str:
if number >= 0: # Get binary representation of positive number
UpperCamelCase__ = "0" + str(bin(_A ) ).strip("-" )[2:]
else: # Get binary (2's complement) representation of negative number
UpperCamelCase__ = len(bin(_A )[3:] ) # Find 2's complement of number
UpperCamelCase__ = bin(abs(_A ) - (1 << binary_number_length) )[3:]
UpperCamelCase__ = (
"1" + "0" * (binary_number_length - len(_A )) + binary_number
)
if shift_amount >= len(_A ):
return "0b" + binary_number[0] * len(_A )
return (
"0b"
+ binary_number[0] * shift_amount
+ binary_number[: len(_A ) - shift_amount]
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 710 |
from collections import deque
def UpperCamelCase_( _A :Union[str, Any] )-> List[Any]:
UpperCamelCase__ = len(_A )
UpperCamelCase__ = deque()
UpperCamelCase__ = [False for _ in range(_A )]
UpperCamelCase__ = [-1 for _ in range(_A )]
UpperCamelCase__ = index_of[:]
def strong_connect(_A :Optional[int] , _A :Optional[int] , _A :List[Any] ):
UpperCamelCase__ = index # the number when this node is seen
UpperCamelCase__ = index # lowest rank node reachable from here
index += 1
stack.append(_A )
UpperCamelCase__ = True
for w in g[v]:
if index_of[w] == -1:
UpperCamelCase__ = strong_connect(_A , _A , _A )
UpperCamelCase__ = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
elif on_stack[w]:
UpperCamelCase__ = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
if lowlink_of[v] == index_of[v]:
UpperCamelCase__ = []
UpperCamelCase__ = stack.pop()
UpperCamelCase__ = False
component.append(_A )
while w != v:
UpperCamelCase__ = stack.pop()
UpperCamelCase__ = False
component.append(_A )
components.append(_A )
return index
UpperCamelCase__ = []
for v in range(_A ):
if index_of[v] == -1:
strong_connect(_A , 0 , _A )
return components
def UpperCamelCase_( _A :Optional[Any] , _A :Any )-> Union[str, Any]:
UpperCamelCase__ = [[] for _ in range(_A )]
for u, v in edges:
g[u].append(_A )
return g
if __name__ == "__main__":
# Test
__UpperCamelCase = 7
__UpperCamelCase = [0, 0, 1, 2, 3, 3, 4, 4, 6]
__UpperCamelCase = [1, 3, 2, 0, 1, 4, 5, 6, 5]
__UpperCamelCase = [(u, v) for u, v in zip(source, target)]
__UpperCamelCase = create_graph(n_vertices, edges)
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
| 185 | 0 |
import math
import os
from copy import deepcopy
import datasets
import evaluate
import torch
import transformers
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from accelerate import Accelerator
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import is_tpu_available, set_seed
lowerCamelCase : Tuple ='''true'''
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase=82 , __lowerCAmelCase=16 ) -> Optional[int]:
set_seed(42 )
UpperCamelCase__ : Union[str, Any] = RegressionModel()
UpperCamelCase__ : Optional[Any] = deepcopy(__lowerCAmelCase )
UpperCamelCase__ : str = RegressionDataset(length=__lowerCAmelCase )
UpperCamelCase__ : int = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase )
model.to(accelerator.device )
UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase , __lowerCAmelCase )
return model, ddp_model, dataloader
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase=False ) -> Dict:
UpperCamelCase__ : Dict = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased" )
UpperCamelCase__ : Optional[Any] = load_dataset("glue" , "mrpc" , split="validation" )
def tokenize_function(__lowerCAmelCase ):
UpperCamelCase__ : Dict = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase )
return outputs
with accelerator.main_process_first():
UpperCamelCase__ : Optional[int] = dataset.map(
__lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , )
UpperCamelCase__ : str = tokenized_datasets.rename_column("label" , "labels" )
def collate_fn(__lowerCAmelCase ):
if use_longest:
return tokenizer.pad(__lowerCAmelCase , padding="longest" , return_tensors="pt" )
return tokenizer.pad(__lowerCAmelCase , padding="max_length" , max_length=128 , return_tensors="pt" )
return DataLoader(__lowerCAmelCase , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=16 )
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]:
UpperCamelCase__ : int = Accelerator(dispatch_batches=__lowerCAmelCase , split_batches=__lowerCAmelCase )
UpperCamelCase__ : int = get_dataloader(__lowerCAmelCase , not dispatch_batches )
UpperCamelCase__ : Any = AutoModelForSequenceClassification.from_pretrained(
"hf-internal-testing/mrpc-bert-base-cased" , return_dict=__lowerCAmelCase )
UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase , __lowerCAmelCase )
return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Dict:
UpperCamelCase__ : List[Any] = []
for batch in dataloader:
UpperCamelCase__ , UpperCamelCase__ : str = batch.values()
with torch.no_grad():
UpperCamelCase__ : Optional[Any] = model(__lowerCAmelCase )
UpperCamelCase__ , UpperCamelCase__ : Tuple = accelerator.gather_for_metrics((logit, target) )
logits_and_targets.append((logit, target) )
UpperCamelCase__ , UpperCamelCase__ : Any = [], []
for logit, targ in logits_and_targets:
logits.append(__lowerCAmelCase )
targs.append(__lowerCAmelCase )
UpperCamelCase__ , UpperCamelCase__ : int = torch.cat(__lowerCAmelCase ), torch.cat(__lowerCAmelCase )
return logits, targs
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase=82 , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=16 ) -> Any:
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Dict = get_basic_setup(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
UpperCamelCase__ , UpperCamelCase__ : List[Any] = generate_predictions(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
assert (
len(__lowerCAmelCase ) == num_samples
), f'Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(__lowerCAmelCase )}'
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase = False , __lowerCAmelCase = False ) -> List[Any]:
UpperCamelCase__ : str = evaluate.load("glue" , "mrpc" )
UpperCamelCase__ , UpperCamelCase__ : Optional[Any] = get_mrpc_setup(__lowerCAmelCase , __lowerCAmelCase )
# First do baseline
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : int = setup["no"]
model.to(__lowerCAmelCase )
model.eval()
for batch in dataloader:
batch.to(__lowerCAmelCase )
with torch.inference_mode():
UpperCamelCase__ : Optional[Any] = model(**__lowerCAmelCase )
UpperCamelCase__ : Union[str, Any] = outputs.logits.argmax(dim=-1 )
metric.add_batch(predictions=__lowerCAmelCase , references=batch["labels"] )
UpperCamelCase__ : Optional[int] = metric.compute()
# Then do distributed
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Dict = setup["ddp"]
model.eval()
for batch in dataloader:
with torch.inference_mode():
UpperCamelCase__ : Optional[Any] = model(**__lowerCAmelCase )
UpperCamelCase__ : Optional[Any] = outputs.logits.argmax(dim=-1 )
UpperCamelCase__ : Dict = batch["labels"]
UpperCamelCase__ , UpperCamelCase__ : List[Any] = accelerator.gather_for_metrics((preds, references) )
metric.add_batch(predictions=__lowerCAmelCase , references=__lowerCAmelCase )
UpperCamelCase__ : str = metric.compute()
for key in "accuracy f1".split():
assert math.isclose(
baseline[key] , distributed[key] ), f'Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n'
def SCREAMING_SNAKE_CASE ( ) -> Optional[int]:
UpperCamelCase__ : Optional[int] = Accelerator(split_batches=__lowerCAmelCase , dispatch_batches=__lowerCAmelCase )
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_warning()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# These are a bit slower so they should only be ran on the GPU or TPU
if torch.cuda.is_available() or is_tpu_available():
if accelerator.is_local_main_process:
print("**Testing gather_for_metrics**" )
for split_batches in [True, False]:
for dispatch_batches in [True, False]:
if accelerator.is_local_main_process:
print(f'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`' )
test_mrpc(__lowerCAmelCase , __lowerCAmelCase )
accelerator.state._reset_state()
if accelerator.is_local_main_process:
print("**Test torch metrics**" )
for split_batches in [True, False]:
for dispatch_batches in [True, False]:
UpperCamelCase__ : Optional[int] = Accelerator(split_batches=__lowerCAmelCase , dispatch_batches=__lowerCAmelCase )
if accelerator.is_local_main_process:
print(f'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99' )
test_torch_metrics(__lowerCAmelCase , 99 )
accelerator.state._reset_state()
if accelerator.is_local_main_process:
print("**Test last batch is not dropped when perfectly divisible**" )
UpperCamelCase__ : Union[str, Any] = Accelerator()
test_torch_metrics(__lowerCAmelCase , 512 )
accelerator.state._reset_state()
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Dict:
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main() | 228 |
import unittest
import numpy as np
import torch
from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class __a ( unittest.TestCase ):
@property
def __lowercase ( self : int ):
'''simple docstring'''
torch.manual_seed(0 )
UpperCamelCase__ : List[Any] = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , )
return model
def __lowercase ( self : int ):
'''simple docstring'''
UpperCamelCase__ : List[str] = self.dummy_uncond_unet
UpperCamelCase__ : List[str] = ScoreSdeVeScheduler()
UpperCamelCase__ : Union[str, Any] = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE )
sde_ve.to(SCREAMING_SNAKE_CASE )
sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[int] = torch.manual_seed(0 )
UpperCamelCase__ : List[Any] = sde_ve(num_inference_steps=2 , output_type="numpy" , generator=SCREAMING_SNAKE_CASE ).images
UpperCamelCase__ : str = torch.manual_seed(0 )
UpperCamelCase__ : Any = sde_ve(num_inference_steps=2 , output_type="numpy" , generator=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE )[
0
]
UpperCamelCase__ : List[str] = image[0, -3:, -3:, -1]
UpperCamelCase__ : Any = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
UpperCamelCase__ : int = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch
class __a ( unittest.TestCase ):
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
UpperCamelCase__ : List[str] = "google/ncsnpp-church-256"
UpperCamelCase__ : Tuple = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Union[str, Any] = ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE )
sde_ve.to(SCREAMING_SNAKE_CASE )
sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = torch.manual_seed(0 )
UpperCamelCase__ : Tuple = sde_ve(num_inference_steps=10 , output_type="numpy" , generator=SCREAMING_SNAKE_CASE ).images
UpperCamelCase__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 2_56, 2_56, 3)
UpperCamelCase__ : Any = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 | 228 | 1 |
from collections.abc import Callable
import numpy as np
def lowerCAmelCase_ ( __UpperCAmelCase: Callable , __UpperCAmelCase: float , __UpperCAmelCase: float , __UpperCAmelCase: float , __UpperCAmelCase: float ) -> np.array:
UpperCamelCase__ : Any = int(np.ceil((x_end - xa) / step_size ) )
UpperCamelCase__ : Optional[int] = np.zeros((n + 1,) )
UpperCamelCase__ : Union[str, Any] = ya
UpperCamelCase__ : List[str] = xa
for k in range(__UpperCAmelCase ):
UpperCamelCase__ : List[str] = y[k] + step_size * ode_func(__UpperCAmelCase , y[k] )
UpperCamelCase__ : List[str] = y[k] + (
(step_size / 2) * (ode_func(__UpperCAmelCase , y[k] ) + ode_func(x + step_size , __UpperCAmelCase ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 369 |
from __future__ import annotations
def lowerCAmelCase_ ( __UpperCAmelCase: str , __UpperCAmelCase: str ) -> bool:
UpperCamelCase__ : List[str] = get_failure_array(__UpperCAmelCase )
# 2) Step through text searching for pattern
UpperCamelCase__ ,UpperCamelCase__ : Dict = 0, 0 # index into text, pattern
while i < len(__UpperCAmelCase ):
if pattern[j] == text[i]:
if j == (len(__UpperCAmelCase ) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
UpperCamelCase__ : Optional[int] = failure[j - 1]
continue
i += 1
return False
def lowerCAmelCase_ ( __UpperCAmelCase: str ) -> list[int]:
UpperCamelCase__ : Union[str, Any] = [0]
UpperCamelCase__ : Tuple = 0
UpperCamelCase__ : Tuple = 1
while j < len(__UpperCAmelCase ):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
UpperCamelCase__ : str = failure[i - 1]
continue
j += 1
failure.append(__UpperCAmelCase )
return failure
if __name__ == "__main__":
# Test 1)
UpperCAmelCase_ = 'abc1abc12'
UpperCAmelCase_ = 'alskfjaldsabc1abc1abc12k23adsfabcabc'
UpperCAmelCase_ = 'alskfjaldsk23adsfabcabc'
assert kmp(pattern, texta) and not kmp(pattern, texta)
# Test 2)
UpperCAmelCase_ = 'ABABX'
UpperCAmelCase_ = 'ABABZABABYABABX'
assert kmp(pattern, text)
# Test 3)
UpperCAmelCase_ = 'AAAB'
UpperCAmelCase_ = 'ABAAAAAB'
assert kmp(pattern, text)
# Test 4)
UpperCAmelCase_ = 'abcdabcy'
UpperCAmelCase_ = 'abcxabcdabxabcdabcdabcy'
assert kmp(pattern, text)
# Test 5)
UpperCAmelCase_ = 'aabaabaaa'
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| 369 | 1 |
def lowerCamelCase__ ( ):
"""simple docstring"""
return 1
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else two_pence(x - 2 ) + one_pence()
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowercase )
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(lowercase )
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(lowercase )
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(lowercase )
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else one_pound(x - 100 ) + fifty_pence(lowercase )
def lowerCamelCase__ ( lowercase ):
"""simple docstring"""
return 0 if x < 0 else two_pound(x - 200 ) + one_pound(lowercase )
def lowerCamelCase__ ( lowercase = 200 ):
"""simple docstring"""
return two_pound(lowercase )
if __name__ == "__main__":
print(solution(int(input().strip())))
| 62 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
UpperCamelCase__ : int = {
'''configuration_poolformer''': [
'''POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''PoolFormerConfig''',
'''PoolFormerOnnxConfig''',
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : List[str] = ['''PoolFormerFeatureExtractor''']
UpperCamelCase__ : Tuple = ['''PoolFormerImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
'''POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''PoolFormerForImageClassification''',
'''PoolFormerModel''',
'''PoolFormerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_poolformer import (
POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
PoolFormerConfig,
PoolFormerOnnxConfig,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_poolformer import PoolFormerFeatureExtractor
from .image_processing_poolformer import PoolFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_poolformer import (
POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
PoolFormerForImageClassification,
PoolFormerModel,
PoolFormerPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure) | 578 | 0 |
"""simple docstring"""
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import flax
import jax
import jax.numpy as jnp
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
CommonSchedulerState,
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
add_noise_common,
get_velocity_common,
)
@flax.struct.dataclass
class lowerCAmelCase__ :
"""simple docstring"""
__UpperCAmelCase : CommonSchedulerState
# setable values
__UpperCAmelCase : jnp.ndarray
__UpperCAmelCase : jnp.ndarray
__UpperCAmelCase : Optional[int] = None
@classmethod
def snake_case ( cls : int , lowercase__ : CommonSchedulerState , lowercase__ : jnp.ndarray , lowercase__ : jnp.ndarray ):
return cls(common=lowercase__ , init_noise_sigma=lowercase__ , timesteps=lowercase__ )
@dataclass
class lowerCAmelCase__ ( lowerCAmelCase_ ):
"""simple docstring"""
__UpperCAmelCase : DDPMSchedulerState
class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
__UpperCAmelCase : Optional[Any] = [e.name for e in FlaxKarrasDiffusionSchedulers]
__UpperCAmelCase : jnp.dtype
@property
def snake_case ( self : Optional[Any] ):
return True
@register_to_config
def __init__( self : Optional[int] , lowercase__ : int = 1_0_0_0 , lowercase__ : float = 0.0_0_0_1 , lowercase__ : float = 0.0_2 , lowercase__ : str = "linear" , lowercase__ : Optional[jnp.ndarray] = None , lowercase__ : str = "fixed_small" , lowercase__ : bool = True , lowercase__ : str = "epsilon" , lowercase__ : jnp.dtype = jnp.floataa , ):
__lowercase : List[Any] = dtype
def snake_case ( self : List[Any] , lowercase__ : Optional[CommonSchedulerState] = None ):
if common is None:
__lowercase : Optional[Any] = CommonSchedulerState.create(self )
# standard deviation of the initial noise distribution
__lowercase : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype )
__lowercase : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1]
return DDPMSchedulerState.create(
common=lowercase__ , init_noise_sigma=lowercase__ , timesteps=lowercase__ , )
def snake_case ( self : str , lowercase__ : DDPMSchedulerState , lowercase__ : jnp.ndarray , lowercase__ : Optional[int] = None ):
return sample
def snake_case ( self : Tuple , lowercase__ : DDPMSchedulerState , lowercase__ : int , lowercase__ : Tuple = () ):
__lowercase : int = self.config.num_train_timesteps // num_inference_steps
# creates integer timesteps by multiplying by ratio
# rounding to avoid issues when num_inference_step is power of 3
__lowercase : List[Any] = (jnp.arange(0 , lowercase__ ) * step_ratio).round()[::-1]
return state.replace(
num_inference_steps=lowercase__ , timesteps=lowercase__ , )
def snake_case ( self : Union[str, Any] , lowercase__ : DDPMSchedulerState , lowercase__ : Optional[int] , lowercase__ : Dict=None , lowercase__ : str=None ):
__lowercase : Optional[int] = state.common.alphas_cumprod[t]
__lowercase : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
# For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
# and sample from it to get previous sample
# x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
__lowercase : Union[str, Any] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t]
if variance_type is None:
__lowercase : Optional[Any] = self.config.variance_type
# hacks - were probably added for training stability
if variance_type == "fixed_small":
__lowercase : Union[str, Any] = jnp.clip(lowercase__ , a_min=1e-20 )
# for rl-diffuser https://arxiv.org/abs/2205.09991
elif variance_type == "fixed_small_log":
__lowercase : List[str] = jnp.log(jnp.clip(lowercase__ , a_min=1e-20 ) )
elif variance_type == "fixed_large":
__lowercase : int = state.common.betas[t]
elif variance_type == "fixed_large_log":
# Glide max_log
__lowercase : Dict = jnp.log(state.common.betas[t] )
elif variance_type == "learned":
return predicted_variance
elif variance_type == "learned_range":
__lowercase : Tuple = variance
__lowercase : Dict = state.common.betas[t]
__lowercase : List[Any] = (predicted_variance + 1) / 2
__lowercase : Optional[Any] = frac * max_log + (1 - frac) * min_log
return variance
def snake_case ( self : Dict , lowercase__ : DDPMSchedulerState , lowercase__ : jnp.ndarray , lowercase__ : int , lowercase__ : jnp.ndarray , lowercase__ : Optional[jax.random.KeyArray] = None , lowercase__ : bool = True , ):
__lowercase : int = timestep
if key is None:
__lowercase : Union[str, Any] = jax.random.PRNGKey(0 )
if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]:
__lowercase ,__lowercase : Union[str, Any] = jnp.split(lowercase__ , sample.shape[1] , axis=1 )
else:
__lowercase : Dict = None
# 1. compute alphas, betas
__lowercase : Dict = state.common.alphas_cumprod[t]
__lowercase : Dict = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
__lowercase : Dict = 1 - alpha_prod_t
__lowercase : List[Any] = 1 - alpha_prod_t_prev
# 2. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
if self.config.prediction_type == "epsilon":
__lowercase : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif self.config.prediction_type == "sample":
__lowercase : str = model_output
elif self.config.prediction_type == "v_prediction":
__lowercase : int = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
else:
raise ValueError(
f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` '
" for the FlaxDDPMScheduler." )
# 3. Clip "predicted x_0"
if self.config.clip_sample:
__lowercase : Dict = jnp.clip(lowercase__ , -1 , 1 )
# 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
__lowercase : Any = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t
__lowercase : Union[str, Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t
# 5. Compute predicted previous sample µ_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
__lowercase : Optional[int] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
def random_variance():
__lowercase : int = jax.random.split(lowercase__ , num=1 )
__lowercase : List[str] = jax.random.normal(lowercase__ , shape=model_output.shape , dtype=self.dtype )
return (self._get_variance(lowercase__ , lowercase__ , predicted_variance=lowercase__ ) ** 0.5) * noise
__lowercase : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) )
__lowercase : List[str] = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample, state)
return FlaxDDPMSchedulerOutput(prev_sample=lowercase__ , state=lowercase__ )
def snake_case ( self : Any , lowercase__ : DDPMSchedulerState , lowercase__ : jnp.ndarray , lowercase__ : jnp.ndarray , lowercase__ : jnp.ndarray , ):
return add_noise_common(state.common , lowercase__ , lowercase__ , lowercase__ )
def snake_case ( self : Optional[int] , lowercase__ : DDPMSchedulerState , lowercase__ : jnp.ndarray , lowercase__ : jnp.ndarray , lowercase__ : jnp.ndarray , ):
return get_velocity_common(state.common , lowercase__ , lowercase__ , lowercase__ )
def __len__( self : Dict ):
return self.config.num_train_timesteps
| 281 |
"""simple docstring"""
import unittest
from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate
def snake_case__ ( _lowerCamelCase ) ->Dict:
"""simple docstring"""
return x + 2
class lowerCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
def snake_case ( self : List[str] ):
__lowercase : List[Any] = "x = 3"
__lowercase : Optional[int] = {}
__lowercase : List[Any] = evaluate(lowercase__ , {} , state=lowercase__ )
assert result == 3
self.assertDictEqual(lowercase__ , {"x": 3} )
__lowercase : Optional[int] = "x = y"
__lowercase : Union[str, Any] = {"y": 5}
__lowercase : str = evaluate(lowercase__ , {} , state=lowercase__ )
# evaluate returns the value of the last assignment.
assert result == 5
self.assertDictEqual(lowercase__ , {"x": 5, "y": 5} )
def snake_case ( self : Dict ):
__lowercase : Dict = "y = add_two(x)"
__lowercase : List[Any] = {"x": 3}
__lowercase : Optional[int] = evaluate(lowercase__ , {"add_two": add_two} , state=lowercase__ )
assert result == 5
self.assertDictEqual(lowercase__ , {"x": 3, "y": 5} )
# Won't work without the tool
with CaptureStdout() as out:
__lowercase : Any = evaluate(lowercase__ , {} , state=lowercase__ )
assert result is None
assert "tried to execute add_two" in out.out
def snake_case ( self : Any ):
__lowercase : Optional[Any] = "x = 3"
__lowercase : List[Any] = {}
__lowercase : Dict = evaluate(lowercase__ , {} , state=lowercase__ )
assert result == 3
self.assertDictEqual(lowercase__ , {"x": 3} )
def snake_case ( self : str ):
__lowercase : Optional[int] = "test_dict = {'x': x, 'y': add_two(x)}"
__lowercase : List[str] = {"x": 3}
__lowercase : Tuple = evaluate(lowercase__ , {"add_two": add_two} , state=lowercase__ )
self.assertDictEqual(lowercase__ , {"x": 3, "y": 5} )
self.assertDictEqual(lowercase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} )
def snake_case ( self : int ):
__lowercase : Tuple = "x = 3\ny = 5"
__lowercase : Optional[Any] = {}
__lowercase : List[Any] = evaluate(lowercase__ , {} , state=lowercase__ )
# evaluate returns the value of the last assignment.
assert result == 5
self.assertDictEqual(lowercase__ , {"x": 3, "y": 5} )
def snake_case ( self : Any ):
__lowercase : str = "text = f'This is x: {x}.'"
__lowercase : Any = {"x": 3}
__lowercase : List[Any] = evaluate(lowercase__ , {} , state=lowercase__ )
# evaluate returns the value of the last assignment.
assert result == "This is x: 3."
self.assertDictEqual(lowercase__ , {"x": 3, "text": "This is x: 3."} )
def snake_case ( self : str ):
__lowercase : Optional[Any] = "if x <= 3:\n y = 2\nelse:\n y = 5"
__lowercase : int = {"x": 3}
__lowercase : Optional[int] = evaluate(lowercase__ , {} , state=lowercase__ )
# evaluate returns the value of the last assignment.
assert result == 2
self.assertDictEqual(lowercase__ , {"x": 3, "y": 2} )
__lowercase : Optional[int] = {"x": 8}
__lowercase : Union[str, Any] = evaluate(lowercase__ , {} , state=lowercase__ )
# evaluate returns the value of the last assignment.
assert result == 5
self.assertDictEqual(lowercase__ , {"x": 8, "y": 5} )
def snake_case ( self : Dict ):
__lowercase : Optional[Any] = "test_list = [x, add_two(x)]"
__lowercase : str = {"x": 3}
__lowercase : Any = evaluate(lowercase__ , {"add_two": add_two} , state=lowercase__ )
self.assertListEqual(lowercase__ , [3, 5] )
self.assertDictEqual(lowercase__ , {"x": 3, "test_list": [3, 5]} )
def snake_case ( self : Optional[int] ):
__lowercase : str = "y = x"
__lowercase : str = {"x": 3}
__lowercase : int = evaluate(lowercase__ , {} , state=lowercase__ )
assert result == 3
self.assertDictEqual(lowercase__ , {"x": 3, "y": 3} )
def snake_case ( self : Optional[int] ):
__lowercase : str = "test_list = [x, add_two(x)]\ntest_list[1]"
__lowercase : Optional[Any] = {"x": 3}
__lowercase : Any = evaluate(lowercase__ , {"add_two": add_two} , state=lowercase__ )
assert result == 5
self.assertDictEqual(lowercase__ , {"x": 3, "test_list": [3, 5]} )
__lowercase : Tuple = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
__lowercase : Union[str, Any] = {"x": 3}
__lowercase : Tuple = evaluate(lowercase__ , {"add_two": add_two} , state=lowercase__ )
assert result == 5
self.assertDictEqual(lowercase__ , {"x": 3, "test_dict": {"x": 3, "y": 5}} )
def snake_case ( self : Dict ):
__lowercase : Dict = "x = 0\nfor i in range(3):\n x = i"
__lowercase : str = {}
__lowercase : int = evaluate(lowercase__ , {"range": range} , state=lowercase__ )
assert result == 2
self.assertDictEqual(lowercase__ , {"x": 2, "i": 2} )
| 281 | 1 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class __magic_name__ ( metaclass=lowercase__ ):
_SCREAMING_SNAKE_CASE : Any = ['keras_nlp']
def __init__( self : List[Any] , *snake_case_ : Union[str, Any] , **snake_case_ : Optional[int] ):
requires_backends(self , ["keras_nlp"] )
| 163 |
"""simple docstring"""
import argparse
import json
import numpy
import torch
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int:
"""simple docstring"""
__snake_case = torch.load(SCREAMING_SNAKE_CASE , map_location="cpu" )
__snake_case = chkpt["model"]
# We have the base model one level deeper than the original XLM repository
__snake_case = {}
for k, v in state_dict.items():
if "pred_layer" in k:
__snake_case = v
else:
__snake_case = v
__snake_case = chkpt["params"]
__snake_case = {n: v for n, v in config.items() if not isinstance(SCREAMING_SNAKE_CASE , (torch.FloatTensor, numpy.ndarray) )}
__snake_case = chkpt["dico_word2id"]
__snake_case = {s + "</w>" if s.find("@@" ) == -1 and i > 13 else s.replace("@@" , "" ): i for s, i in vocab.items()}
# Save pytorch-model
__snake_case = pytorch_dump_folder_path + "/" + WEIGHTS_NAME
__snake_case = pytorch_dump_folder_path + "/" + CONFIG_NAME
__snake_case = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"]
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(SCREAMING_SNAKE_CASE , indent=2 ) + "\n" )
print(F'''Save vocab file to {pytorch_config_dump_path}''' )
with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(SCREAMING_SNAKE_CASE , indent=2 ) + "\n" )
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--xlm_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump."""
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
_SCREAMING_SNAKE_CASE = parser.parse_args()
convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
| 163 | 1 |
from __future__ import annotations
import unittest
import numpy as np
from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
if is_tf_available():
import tensorflow as tf
from transformers import TFBlipTextModel
from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST
class a :
def __init__( self : Dict, SCREAMING_SNAKE_CASE_ : List[Any], SCREAMING_SNAKE_CASE_ : Optional[int]=12, SCREAMING_SNAKE_CASE_ : Optional[Any]=7, SCREAMING_SNAKE_CASE_ : str=True, SCREAMING_SNAKE_CASE_ : str=True, SCREAMING_SNAKE_CASE_ : Optional[int]=True, SCREAMING_SNAKE_CASE_ : List[Any]=99, SCREAMING_SNAKE_CASE_ : Tuple=32, SCREAMING_SNAKE_CASE_ : List[str]=32, SCREAMING_SNAKE_CASE_ : Any=2, SCREAMING_SNAKE_CASE_ : Dict=4, SCREAMING_SNAKE_CASE_ : int=37, SCREAMING_SNAKE_CASE_ : int=0.1, SCREAMING_SNAKE_CASE_ : List[str]=0.1, SCREAMING_SNAKE_CASE_ : int=5_12, SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.02, SCREAMING_SNAKE_CASE_ : Tuple=0, SCREAMING_SNAKE_CASE_ : List[str]=None, ):
snake_case : str = parent
snake_case : List[Any] = batch_size
snake_case : Optional[Any] = seq_length
snake_case : Optional[Any] = is_training
snake_case : List[str] = use_input_mask
snake_case : List[Any] = use_labels
snake_case : List[Any] = vocab_size
snake_case : Optional[int] = hidden_size
snake_case : int = projection_dim
snake_case : Tuple = num_hidden_layers
snake_case : Dict = num_attention_heads
snake_case : Any = intermediate_size
snake_case : Dict = dropout
snake_case : Any = attention_dropout
snake_case : Any = max_position_embeddings
snake_case : List[str] = initializer_range
snake_case : Dict = scope
snake_case : List[Any] = bos_token_id
def __snake_case ( self : str ):
snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size )
snake_case : Union[str, Any] = None
if self.use_input_mask:
snake_case : int = random_attention_mask([self.batch_size, self.seq_length] )
if input_mask is not None:
snake_case : Optional[Any] = input_mask.numpy()
snake_case : Any = input_mask.shape
snake_case : str = np.random.randint(1, seq_length - 1, size=(batch_size,) )
for batch_idx, start_index in enumerate(SCREAMING_SNAKE_CASE_ ):
snake_case : List[Any] = 1
snake_case : Union[str, Any] = 0
snake_case : Optional[Any] = self.get_config()
return config, input_ids, tf.convert_to_tensor(SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Dict ):
return BlipTextConfig(
vocab_size=self.vocab_size, hidden_size=self.hidden_size, projection_dim=self.projection_dim, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, bos_token_id=self.bos_token_id, )
def __snake_case ( self : int, SCREAMING_SNAKE_CASE_ : int, SCREAMING_SNAKE_CASE_ : Tuple, SCREAMING_SNAKE_CASE_ : Optional[Any] ):
snake_case : Optional[int] = TFBlipTextModel(config=SCREAMING_SNAKE_CASE_ )
snake_case : Optional[Any] = model(SCREAMING_SNAKE_CASE_, attention_mask=SCREAMING_SNAKE_CASE_, training=SCREAMING_SNAKE_CASE_ )
snake_case : Union[str, Any] = model(SCREAMING_SNAKE_CASE_, training=SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size) )
def __snake_case ( self : int ):
snake_case : Optional[Any] = self.prepare_config_and_inputs()
snake_case : Dict = config_and_inputs
snake_case : Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_tf
class a ( __magic_name__ ,unittest.TestCase ):
_snake_case = (TFBlipTextModel,) if is_tf_available() else ()
_snake_case = False
_snake_case = False
_snake_case = False
def __snake_case ( self : str ):
snake_case : List[Any] = BlipTextModelTester(self )
snake_case : int = ConfigTester(self, config_class=SCREAMING_SNAKE_CASE_, hidden_size=37 )
def __snake_case ( self : Dict ):
self.config_tester.run_common_tests()
def __snake_case ( self : List[str] ):
snake_case : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Dict ):
pass
def __snake_case ( self : Dict ):
pass
@unittest.skip(reason='''Blip does not use inputs_embeds''' )
def __snake_case ( self : Optional[int] ):
pass
@unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' )
def __snake_case ( self : Any ):
pass
@unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' )
def __snake_case ( self : List[str] ):
pass
@slow
def __snake_case ( self : int ):
for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case : int = TFBlipTextModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : str, SCREAMING_SNAKE_CASE_ : Union[str, Any]=True ):
super().test_pt_tf_model_equivalence(allow_missing_keys=SCREAMING_SNAKE_CASE_ )
| 704 |
'''simple docstring'''
import argparse
import json
import math
import os
import time
import traceback
import zipfile
from collections import Counter
import requests
def A ( A_ : List[Any] , A_ : int=None ):
snake_case : Optional[int] = None
if token is not None:
snake_case : List[Any] = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': F"""Bearer {token}"""}
snake_case : str = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"""
snake_case : List[Any] = requests.get(A_ , headers=A_ ).json()
snake_case : List[Any] = {}
try:
job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} )
snake_case : Optional[Any] = math.ceil((result['''total_count'''] - 100) / 100 )
for i in range(A_ ):
snake_case : Optional[Any] = requests.get(url + F"""&page={i + 2}""" , headers=A_ ).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 ( A_ : int , A_ : Optional[int]=None ):
snake_case : Any = None
if token is not None:
snake_case : str = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': F"""Bearer {token}"""}
snake_case : Tuple = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100"""
snake_case : List[Any] = requests.get(A_ , headers=A_ ).json()
snake_case : List[Any] = {}
try:
artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} )
snake_case : Dict = math.ceil((result['''total_count'''] - 100) / 100 )
for i in range(A_ ):
snake_case : List[Any] = requests.get(url + F"""&page={i + 2}""" , headers=A_ ).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 ( A_ : List[Any] , A_ : List[Any] , A_ : Any , A_ : str ):
snake_case : Any = None
if token is not None:
snake_case : int = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': F"""Bearer {token}"""}
snake_case : Any = requests.get(A_ , headers=A_ , allow_redirects=A_ )
snake_case : Union[str, Any] = result.headers['''Location''']
snake_case : str = requests.get(A_ , allow_redirects=A_ )
snake_case : int = os.path.join(A_ , F"""{artifact_name}.zip""" )
with open(A_ , '''wb''' ) as fp:
fp.write(response.content )
def A ( A_ : int , A_ : Any=None ):
snake_case : Optional[int] = []
snake_case : Any = []
snake_case : str = None
with zipfile.ZipFile(A_ ) as z:
for filename in z.namelist():
if not os.path.isdir(A_ ):
# read the file
if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]:
with z.open(A_ ) as f:
for line in f:
snake_case : Optional[int] = line.decode('''UTF-8''' ).strip()
if filename == "failures_line.txt":
try:
# `error_line` is the place where `error` occurs
snake_case : List[str] = line[: line.index(''': ''' )]
snake_case : List[Any] = 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
snake_case : List[Any] = line[len('''FAILED ''' ) :]
failed_tests.append(A_ )
elif filename == "job_name.txt":
snake_case : Optional[int] = line
if len(A_ ) != len(A_ ):
raise ValueError(
F"""`errors` and `failed_tests` should have the same number of elements. Got {len(A_ )} for `errors` """
F"""and {len(A_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some"""
''' problem.''' )
snake_case : int = None
if job_name and job_links:
snake_case : int = job_links.get(A_ , A_ )
# A list with elements of the form (line of error, error, failed test)
snake_case : Tuple = [x + [y] + [job_link] for x, y in zip(A_ , A_ )]
return result
def A ( A_ : Optional[Any] , A_ : List[str]=None ):
snake_case : str = []
snake_case : str = [os.path.join(A_ , A_ ) for p in os.listdir(A_ ) if p.endswith('''.zip''' )]
for p in paths:
errors.extend(get_errors_from_single_artifact(A_ , job_links=A_ ) )
return errors
def A ( A_ : Dict , A_ : Optional[Any]=None ):
snake_case : Any = Counter()
counter.update([x[1] for x in logs] )
snake_case : Optional[Any] = counter.most_common()
snake_case : Dict = {}
for error, count in counts:
if error_filter is None or error not in error_filter:
snake_case : str = {'''count''': count, '''failed_tests''': [(x[2], x[0]) for x in logs if x[1] == error]}
snake_case : Dict = dict(sorted(r.items() , key=lambda A_ : item[1]["count"] , reverse=A_ ) )
return r
def A ( A_ : Tuple ):
snake_case : Tuple = test.split('''::''' )[0]
if test.startswith('''tests/models/''' ):
snake_case : Optional[int] = test.split('''/''' )[2]
else:
snake_case : int = None
return test
def A ( A_ : Optional[Any] , A_ : Dict=None ):
snake_case : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs]
snake_case : int = [x for x in logs if x[2] is not None]
snake_case : int = {x[2] for x in logs}
snake_case : List[str] = {}
for test in tests:
snake_case : Dict = Counter()
# count by errors in `test`
counter.update([x[1] for x in logs if x[2] == test] )
snake_case : Optional[Any] = counter.most_common()
snake_case : str = {error: count for error, count in counts if (error_filter is None or error not in error_filter)}
snake_case : List[Any] = sum(error_counts.values() )
if n_errors > 0:
snake_case : Optional[Any] = {'''count''': n_errors, '''errors''': error_counts}
snake_case : Optional[int] = dict(sorted(r.items() , key=lambda A_ : item[1]["count"] , reverse=A_ ) )
return r
def A ( A_ : Optional[Any] ):
snake_case : Dict = '''| no. | error | status |'''
snake_case : Union[str, Any] = '''|-:|:-|:-|'''
snake_case : List[Any] = [header, sep]
for error in reduced_by_error:
snake_case : Optional[int] = reduced_by_error[error]['''count''']
snake_case : List[str] = F"""| {count} | {error[:100]} | |"""
lines.append(A_ )
return "\n".join(A_ )
def A ( A_ : Optional[int] ):
snake_case : Union[str, Any] = '''| model | no. of errors | major error | count |'''
snake_case : Dict = '''|-:|-:|-:|-:|'''
snake_case : Optional[Any] = [header, sep]
for model in reduced_by_model:
snake_case : str = reduced_by_model[model]['''count''']
snake_case, snake_case : Tuple = list(reduced_by_model[model]['''errors'''].items() )[0]
snake_case : Dict = F"""| {model} | {count} | {error[:60]} | {_count} |"""
lines.append(A_ )
return "\n".join(A_ )
if __name__ == "__main__":
UpperCAmelCase = 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.")
UpperCAmelCase = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
UpperCAmelCase = get_job_links(args.workflow_run_id, token=args.token)
UpperCAmelCase = {}
# 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:
UpperCAmelCase = k.find(" / ")
UpperCAmelCase = k[index + len(" / ") :]
UpperCAmelCase = 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)
UpperCAmelCase = 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)
UpperCAmelCase = get_all_errors(args.output_dir, job_links=job_links)
# `e[1]` is the error
UpperCAmelCase = Counter()
counter.update([e[1] for e in errors])
# print the top 30 most common test errors
UpperCAmelCase = 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)
UpperCAmelCase = reduce_by_error(errors)
UpperCAmelCase = reduce_by_model(errors)
UpperCAmelCase = make_github_table(reduced_by_error)
UpperCAmelCase = 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)
| 555 | 0 |
'''simple docstring'''
import argparse
import json
from typing import List
from ltp import LTP
from transformers.models.bert.tokenization_bert import BertTokenizer
def _UpperCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
if (
(cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F)
or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) #
or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) #
or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) #
or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) #
or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) #
or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F)
or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) #
): #
return True
return False
def _UpperCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
for char in word:
__magic_name__ : Optional[int] = ord(lowerCamelCase_ )
if not _is_chinese_char(lowerCamelCase_ ):
return 0
return 1
def _UpperCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
__magic_name__ : Union[str, Any] = set()
for token in tokens:
__magic_name__ : Any = len(lowerCamelCase_ ) > 1 and is_chinese(lowerCamelCase_ )
if chinese_word:
word_set.add(lowerCamelCase_ )
__magic_name__ : str = list(lowerCamelCase_ )
return word_list
def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ):
"""simple docstring"""
if not chinese_word_set:
return bert_tokens
__magic_name__ : Tuple = max([len(lowerCamelCase_ ) for w in chinese_word_set] )
__magic_name__ : List[str] = bert_tokens
__magic_name__ : Tuple = 0, len(lowerCamelCase_ )
while start < end:
__magic_name__ : List[str] = True
if is_chinese(bert_word[start] ):
__magic_name__ : List[str] = min(end - start , lowerCamelCase_ )
for i in range(lowerCamelCase_ , 1 , -1 ):
__magic_name__ : Optional[int] = ''.join(bert_word[start : start + i] )
if whole_word in chinese_word_set:
for j in range(start + 1 , start + i ):
__magic_name__ : Optional[Any] = '##' + bert_word[j]
__magic_name__ : List[Any] = start + i
__magic_name__ : Tuple = False
break
if single_word:
start += 1
return bert_word
def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
"""simple docstring"""
__magic_name__ : Union[str, Any] = []
for i in range(0 , len(lowerCamelCase_ ) , 100 ):
__magic_name__ : List[Any] = ltp_tokenizer.pipeline(lines[i : i + 100] , tasks=["cws"] ).cws
__magic_name__ : Optional[int] = [get_chinese_word(lowerCamelCase_ ) for r in res]
ltp_res.extend(lowerCamelCase_ )
assert len(lowerCamelCase_ ) == len(lowerCamelCase_ )
__magic_name__ : Optional[Any] = []
for i in range(0 , len(lowerCamelCase_ ) , 100 ):
__magic_name__ : Union[str, Any] = bert_tokenizer(lines[i : i + 100] , add_special_tokens=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=512 )
bert_res.extend(res["input_ids"] )
assert len(lowerCamelCase_ ) == len(lowerCamelCase_ )
__magic_name__ : Union[str, Any] = []
for input_ids, chinese_word in zip(lowerCamelCase_ , lowerCamelCase_ ):
__magic_name__ : str = []
for id in input_ids:
__magic_name__ : Optional[int] = bert_tokenizer._convert_id_to_token(lowerCamelCase_ )
input_tokens.append(lowerCamelCase_ )
__magic_name__ : int = add_sub_symbol(lowerCamelCase_ , lowerCamelCase_ )
__magic_name__ : List[Any] = []
# We only save pos of chinese subwords start with ##, which mean is part of a whole word.
for i, token in enumerate(lowerCamelCase_ ):
if token[:2] == "##":
__magic_name__ : Dict = token[2:]
# save chinese tokens' pos
if len(lowerCamelCase_ ) == 1 and _is_chinese_char(ord(lowerCamelCase_ ) ):
ref_id.append(lowerCamelCase_ )
ref_ids.append(lowerCamelCase_ )
assert len(lowerCamelCase_ ) == len(lowerCamelCase_ )
return ref_ids
def _UpperCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
with open(args.file_name , "r" , encoding="utf-8" ) as f:
__magic_name__ : int = f.readlines()
__magic_name__ : Optional[Any] = [line.strip() for line in data if len(lowerCamelCase_ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029'
__magic_name__ : int = LTP(args.ltp ) # faster in GPU device
__magic_name__ : Dict = BertTokenizer.from_pretrained(args.bert )
__magic_name__ : Union[str, Any] = prepare_ref(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
with open(args.save_path , "w" , encoding="utf-8" ) as f:
__magic_name__ : Union[str, Any] = [json.dumps(lowerCamelCase_ ) + '\n' for ref in ref_ids]
f.writelines(lowerCamelCase_ )
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser(description="prepare_chinese_ref")
parser.add_argument(
"--file_name",
required=False,
type=str,
default="./resources/chinese-demo.txt",
help="file need process, same as training data in lm",
)
parser.add_argument(
"--ltp",
required=False,
type=str,
default="./resources/ltp",
help="resources for LTP tokenizer, usually a path",
)
parser.add_argument(
"--bert",
required=False,
type=str,
default="./resources/robert",
help="resources for Bert tokenizer",
)
parser.add_argument(
"--save_path",
required=False,
type=str,
default="./resources/ref.txt",
help="path to save res",
)
_SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args()
main(args) | 436 |
import json
import os
import shutil
import tempfile
from unittest import TestCase
from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available
if is_torch_available() and is_datasets_available() and is_faiss_available():
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.tokenization_rag import RagTokenizer
@require_faiss
@require_torch
class _UpperCamelCase( __lowerCamelCase ):
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
__a : List[Any] = tempfile.mkdtemp()
__a : int = 8
# DPR tok
__a : Dict = [
'[UNK]',
'[CLS]',
'[SEP]',
'[PAD]',
'[MASK]',
'want',
'##want',
'##ed',
'wa',
'un',
'runn',
'##ing',
',',
'low',
'lowest',
]
__a : int = os.path.join(self.tmpdirname , 'dpr_tokenizer' )
os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ )
__a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , DPR_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] ) )
# BART tok
__a : str = [
'l',
'o',
'w',
'e',
'r',
's',
't',
'i',
'd',
'n',
'\u0120',
'\u0120l',
'\u0120n',
'\u0120lo',
'\u0120low',
'er',
'\u0120lowest',
'\u0120newer',
'\u0120wider',
'<unk>',
]
__a : Optional[int] = dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) )
__a : List[str] = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
__a : List[str] = {'unk_token': '<unk>'}
__a : Dict = os.path.join(self.tmpdirname , 'bart_tokenizer' )
os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ )
__a : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['vocab_file'] )
__a : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , BART_VOCAB_FILES_NAMES['merges_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp:
fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(SCREAMING_SNAKE_CASE__ ) )
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) )
def __lowerCAmelCase ( self : str ):
'''simple docstring'''
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer' ) )
def __lowerCAmelCase ( self : Union[str, Any] ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
@require_tokenizers
def __lowerCAmelCase ( self : Dict ):
'''simple docstring'''
__a : Tuple = os.path.join(self.tmpdirname , 'rag_tokenizer' )
__a : Optional[Any] = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() )
__a : Optional[Any] = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() )
rag_config.save_pretrained(SCREAMING_SNAKE_CASE__ )
rag_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ )
__a : List[Any] = RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ )
self.assertIsInstance(new_rag_tokenizer.question_encoder , SCREAMING_SNAKE_CASE__ )
self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() )
self.assertIsInstance(new_rag_tokenizer.generator , SCREAMING_SNAKE_CASE__ )
self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() )
@slow
def __lowerCAmelCase ( self : Optional[Any] ):
'''simple docstring'''
__a : Optional[Any] = RagTokenizer.from_pretrained('facebook/rag-token-nq' )
__a : List[Any] = [
'who got the first nobel prize in physics',
'when is the next deadpool movie being released',
'which mode is used for short wave broadcast service',
'who is the owner of reading football club',
'when is the next scandal episode coming out',
'when is the last time the philadelphia won the superbowl',
'what is the most current adobe flash player version',
'how many episodes are there in dragon ball z',
'what is the first step in the evolution of the eye',
'where is gall bladder situated in human body',
'what is the main mineral in lithium batteries',
'who is the president of usa right now',
'where do the greasers live in the outsiders',
'panda is a national animal of which country',
'what is the name of manchester united stadium',
]
__a : Tuple = tokenizer(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
@slow
def __lowerCAmelCase ( self : Optional[int] ):
'''simple docstring'''
__a : Any = RagTokenizer.from_pretrained('facebook/rag-sequence-nq' )
__a : Union[str, Any] = [
'who got the first nobel prize in physics',
'when is the next deadpool movie being released',
'which mode is used for short wave broadcast service',
'who is the owner of reading football club',
'when is the next scandal episode coming out',
'when is the last time the philadelphia won the superbowl',
'what is the most current adobe flash player version',
'how many episodes are there in dragon ball z',
'what is the first step in the evolution of the eye',
'where is gall bladder situated in human body',
'what is the main mineral in lithium batteries',
'who is the president of usa right now',
'where do the greasers live in the outsiders',
'panda is a national animal of which country',
'what is the name of manchester united stadium',
]
__a : str = tokenizer(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
| 47 | 0 |
"""simple docstring"""
import numpy as np
import skfuzzy as fuzz
if __name__ == "__main__":
# Create universe of discourse in Python using linspace ()
A_ = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False)
# Create two fuzzy sets by defining any membership function
# (trapmf(), gbellmf(), gaussmf(), etc).
A_ = [0, 25, 50]
A_ = [25, 50, 75]
A_ = fuzz.membership.trimf(X, abca)
A_ = fuzz.membership.trimf(X, abca)
# Compute the different operations using inbuilt functions.
A_ = np.ones(75)
A_ = np.zeros((75,))
# 1. Union = max(µA(x), µB(x))
A_ = fuzz.fuzzy_or(X, young, X, middle_aged)[1]
# 2. Intersection = min(µA(x), µB(x))
A_ = fuzz.fuzzy_and(X, young, X, middle_aged)[1]
# 3. Complement (A) = (1- min(µA(x))
A_ = fuzz.fuzzy_not(young)
# 4. Difference (A/B) = min(µA(x),(1- µB(x)))
A_ = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1]
# 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]
A_ = young + middle_aged - (young * middle_aged)
# 6. Algebraic Product = (µA(x) * µB(x))
A_ = young * middle_aged
# 7. Bounded Sum = min[1,(µA(x), µB(x))]
A_ = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1]
# 8. Bounded difference = min[0,(µA(x), µB(x))]
A_ = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1]
# max-min composition
# max-product composition
# Plot each set A, set B and each operation result using plot() and subplot().
from matplotlib import pyplot as plt
plt.figure()
plt.subplot(4, 3, 1)
plt.plot(X, young)
plt.title('''Young''')
plt.grid(True)
plt.subplot(4, 3, 2)
plt.plot(X, middle_aged)
plt.title('''Middle aged''')
plt.grid(True)
plt.subplot(4, 3, 3)
plt.plot(X, union)
plt.title('''union''')
plt.grid(True)
plt.subplot(4, 3, 4)
plt.plot(X, intersection)
plt.title('''intersection''')
plt.grid(True)
plt.subplot(4, 3, 5)
plt.plot(X, complement_a)
plt.title('''complement_a''')
plt.grid(True)
plt.subplot(4, 3, 6)
plt.plot(X, difference)
plt.title('''difference a/b''')
plt.grid(True)
plt.subplot(4, 3, 7)
plt.plot(X, alg_sum)
plt.title('''alg_sum''')
plt.grid(True)
plt.subplot(4, 3, 8)
plt.plot(X, alg_product)
plt.title('''alg_product''')
plt.grid(True)
plt.subplot(4, 3, 9)
plt.plot(X, bdd_sum)
plt.title('''bdd_sum''')
plt.grid(True)
plt.subplot(4, 3, 10)
plt.plot(X, bdd_difference)
plt.title('''bdd_difference''')
plt.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show()
| 718 |
"""simple docstring"""
import warnings
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
A_ = logging.get_logger(__name__)
class __SCREAMING_SNAKE_CASE ( UpperCamelCase ):
snake_case_ = ['input_values', 'attention_mask']
def __init__( self : Union[str, Any] , snake_case : int = 1 , snake_case : int = 1_6000 , snake_case : float = 0.0 , snake_case : bool = False , snake_case : int = 80 , snake_case : int = 16 , snake_case : int = 64 , snake_case : str = "hann_window" , snake_case : float = 1.0 , snake_case : float = 80 , snake_case : float = 7600 , snake_case : float = 1e-10 , snake_case : int = 2 , snake_case : bool = True , **snake_case : Dict , ):
'''simple docstring'''
super().__init__(feature_size=snake_case , sampling_rate=snake_case , padding_value=snake_case , **snake_case )
A__ : Optional[int] = do_normalize
A__ : List[Any] = return_attention_mask
A__ : Tuple = num_mel_bins
A__ : Optional[int] = hop_length
A__ : List[str] = win_length
A__ : List[Any] = win_function
A__ : Tuple = frame_signal_scale
A__ : Optional[Any] = fmin
A__ : str = fmax
A__ : str = mel_floor
A__ : Dict = reduction_factor
A__ : int = win_length * sampling_rate // 1000
A__ : Optional[Any] = hop_length * sampling_rate // 1000
A__ : Optional[int] = optimal_fft_length(self.sample_size )
A__ : List[Any] = (self.n_fft // 2) + 1
A__ : str = window_function(window_length=self.sample_size , name=self.win_function , periodic=snake_case )
A__ : Optional[Any] = mel_filter_bank(
num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm="""slaney""" , mel_scale="""slaney""" , )
if frame_signal_scale != 1.0:
warnings.warn(
"""The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers""" , snake_case , )
if reduction_factor != 2.0:
warnings.warn(
"""The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers""" , snake_case , )
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def _UpperCamelCase ( snake_case : List[np.ndarray] , snake_case : List[np.ndarray] , snake_case : float = 0.0 ):
'''simple docstring'''
if attention_mask is not None:
A__ : Tuple = np.array(snake_case , np.intaa )
A__ : List[Any] = []
for vector, length in zip(snake_case , attention_mask.sum(-1 ) ):
A__ : str = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 )
if length < normed_slice.shape[0]:
A__ : int = padding_value
normed_input_values.append(snake_case )
else:
A__ : List[Any] = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values]
return normed_input_values
def _UpperCamelCase ( self : Optional[int] , snake_case : np.ndarray , ):
'''simple docstring'''
A__ : List[Any] = spectrogram(
snake_case , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel="""log10""" , )
return log_mel_spec.T
def __call__( self : str , snake_case : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , snake_case : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , snake_case : Union[bool, str, PaddingStrategy] = False , snake_case : Optional[int] = None , snake_case : bool = False , snake_case : Optional[int] = None , snake_case : Optional[bool] = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : Optional[int] = None , **snake_case : Union[str, Any] , ):
'''simple docstring'''
if audio is None and audio_target is None:
raise ValueError("""You must provide either `audio` or `audio_target` values.""" )
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'
F' {self.sampling_rate} and not {sampling_rate}.' )
else:
logger.warning(
"""It is strongly recommended to pass the ``sampling_rate`` argument to this function. """
"""Failing to do so can result in silent errors that might be hard to debug.""" )
if audio is not None:
A__ : Dict = self._process_audio(
snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , **snake_case , )
else:
A__ : Dict = None
if audio_target is not None:
A__ : Union[str, Any] = self._process_audio(
snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , **snake_case , )
if inputs is None:
return inputs_target
else:
A__ : Union[str, Any] = inputs_target["""input_values"""]
A__ : str = inputs_target.get("""attention_mask""" )
if decoder_attention_mask is not None:
A__ : List[str] = decoder_attention_mask
return inputs
def _UpperCamelCase ( self : str , snake_case : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , snake_case : bool = False , snake_case : Union[bool, str, PaddingStrategy] = False , snake_case : Optional[int] = None , snake_case : bool = False , snake_case : Optional[int] = None , snake_case : Optional[bool] = None , snake_case : Optional[Union[str, TensorType]] = None , **snake_case : Union[str, Any] , ):
'''simple docstring'''
A__ : List[str] = isinstance(snake_case , np.ndarray ) and len(speech.shape ) > 1
if is_batched_numpy and len(speech.shape ) > 2:
raise ValueError(F'Only mono-channel audio is supported for input to {self}' )
A__ : Tuple = is_batched_numpy or (
isinstance(snake_case , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
A__ : Tuple = [np.asarray(snake_case , dtype=np.floataa ) for speech in speech]
elif not is_batched and not isinstance(snake_case , np.ndarray ):
A__ : Tuple = np.asarray(snake_case , dtype=np.floataa )
elif isinstance(snake_case , np.ndarray ) and speech.dtype is np.dtype(np.floataa ):
A__ : str = speech.astype(np.floataa )
# always return batch
if not is_batched:
A__ : Optional[Any] = [speech]
# needed to make pad() work on spectrogram inputs
A__ : str = self.feature_size
# convert into correct format for padding
if is_target:
A__ : str = [self._extract_mel_features(snake_case ) for waveform in speech]
A__ : List[str] = BatchFeature({"""input_values""": features} )
A__ : Dict = self.num_mel_bins
else:
A__ : Tuple = BatchFeature({"""input_values""": speech} )
A__ : List[str] = self.pad(
snake_case , padding=snake_case , max_length=snake_case , truncation=snake_case , pad_to_multiple_of=snake_case , return_attention_mask=snake_case , **snake_case , )
A__ : List[str] = feature_size_hack
# convert input values to correct format
A__ : str = padded_inputs["""input_values"""]
if not isinstance(input_values[0] , np.ndarray ):
A__ : Tuple = [np.asarray(snake_case , dtype=np.floataa ) for array in input_values]
elif (
not isinstance(snake_case , np.ndarray )
and isinstance(input_values[0] , np.ndarray )
and input_values[0].dtype is np.dtype(np.floataa )
):
A__ : Dict = [array.astype(np.floataa ) for array in input_values]
elif isinstance(snake_case , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ):
A__ : Any = input_values.astype(np.floataa )
# convert attention_mask to correct format
A__ : List[Any] = padded_inputs.get("""attention_mask""" )
if attention_mask is not None:
A__ : Any = [np.asarray(snake_case , dtype=np.intaa ) for array in attention_mask]
# zero-mean and unit-variance normalization
if not is_target and self.do_normalize:
A__ : Optional[int] = (
attention_mask
if self._get_padding_strategies(snake_case , max_length=snake_case ) is not PaddingStrategy.DO_NOT_PAD
else None
)
A__ : Optional[int] = self.zero_mean_unit_var_norm(
padded_inputs["""input_values"""] , attention_mask=snake_case , padding_value=self.padding_value )
if return_tensors is not None:
A__ : Any = padded_inputs.convert_to_tensors(snake_case )
return padded_inputs
def _UpperCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
A__ : List[str] = super().to_dict()
# Don't serialize these as they are derived from the other properties.
A__ : Dict = ["""window""", """mel_filters""", """sample_size""", """sample_stride""", """n_fft""", """n_freqs"""]
for name in names:
if name in output:
del output[name]
return output
| 498 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase : Dict = logging.get_logger(__name__)
UpperCamelCase : Tuple = {
"""naver-clova-ix/donut-base""": """https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json""",
# See all Donut models at https://huggingface.co/models?filter=donut-swin
}
class A__ ( A__ ):
"""simple docstring"""
_lowercase = 'donut-swin'
_lowercase = {
'num_attention_heads': 'num_heads',
'num_hidden_layers': 'num_layers',
}
def __init__( self : Any , lowerCamelCase__ : Optional[Any]=224 , lowerCamelCase__ : Tuple=4 , lowerCamelCase__ : str=3 , lowerCamelCase__ : Union[str, Any]=96 , lowerCamelCase__ : Optional[int]=[2, 2, 6, 2] , lowerCamelCase__ : str=[3, 6, 12, 24] , lowerCamelCase__ : List[str]=7 , lowerCamelCase__ : int=4.0 , lowerCamelCase__ : Any=True , lowerCamelCase__ : Tuple=0.0 , lowerCamelCase__ : Optional[Any]=0.0 , lowerCamelCase__ : int=0.1 , lowerCamelCase__ : List[Any]="gelu" , lowerCamelCase__ : List[str]=False , lowerCamelCase__ : Optional[int]=0.02 , lowerCamelCase__ : Dict=1E-5 , **lowerCamelCase__ : Optional[int] , ):
super().__init__(**lowerCamelCase__ )
a__ : Tuple = image_size
a__ : str = patch_size
a__ : Tuple = num_channels
a__ : Any = embed_dim
a__ : int = depths
a__ : List[str] = len(lowerCamelCase__ )
a__ : Optional[Any] = num_heads
a__ : Dict = window_size
a__ : Optional[int] = mlp_ratio
a__ : List[Any] = qkv_bias
a__ : Tuple = hidden_dropout_prob
a__ : int = attention_probs_dropout_prob
a__ : Union[str, Any] = drop_path_rate
a__ : List[str] = hidden_act
a__ : Optional[Any] = use_absolute_embeddings
a__ : Union[str, Any] = layer_norm_eps
a__ : Optional[int] = initializer_range
# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
a__ : Any = int(embed_dim * 2 ** (len(lowerCamelCase__ ) - 1) )
| 37 |
"""simple docstring"""
def _lowerCamelCase ( _UpperCamelCase ):
'''simple docstring'''
__lowerCAmelCase = False
while is_sorted is False: # Until all the indices are traversed keep looping
__lowerCAmelCase = True
for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
__lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i]
# swapping if elements not in order
__lowerCAmelCase = False
for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
__lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i]
# swapping if elements not in order
__lowerCAmelCase = False
return input_list
if __name__ == "__main__":
print("Enter list to be sorted")
A : Tuple = [int(x) for x in input().split()]
# inputing elements of the list in one line
A : Dict = odd_even_sort(input_list)
print("The sorted list is")
print(sorted_list)
| 636 | 0 |
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def _lowerCAmelCase ( A__ ):
lowercase__ = int(number**0.5 )
return number == sq * sq
def _lowerCAmelCase ( A__ , A__ , A__ , A__ , A__ , A__ ):
lowercase__ = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
lowercase__ = x_den * y_den * z_den
lowercase__ = gcd(lowerCAmelCase_ , lowerCAmelCase_ )
top //= hcf
bottom //= hcf
return top, bottom
def _lowerCAmelCase ( A__ = 35 ):
lowercase__ = set()
lowercase__ = 42
lowercase__ = Fraction(0 )
lowercase__ = 42
for x_num in range(1 , order + 1 ):
for x_den in range(x_num + 1 , order + 1 ):
for y_num in range(1 , order + 1 ):
for y_den in range(y_num + 1 , order + 1 ):
# n=1
lowercase__ = x_num * y_den + x_den * y_num
lowercase__ = x_den * y_den
lowercase__ = gcd(lowerCAmelCase_ , lowerCAmelCase_ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase__ = add_three(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
unique_s.add(lowerCAmelCase_ )
# n=2
lowercase__ = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
lowercase__ = x_den * x_den * y_den * y_den
if is_sq(lowerCAmelCase_ ) and is_sq(lowerCAmelCase_ ):
lowercase__ = int(sqrt(lowerCAmelCase_ ) )
lowercase__ = int(sqrt(lowerCAmelCase_ ) )
lowercase__ = gcd(lowerCAmelCase_ , lowerCAmelCase_ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase__ = add_three(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
unique_s.add(lowerCAmelCase_ )
# n=-1
lowercase__ = x_num * y_num
lowercase__ = x_den * y_num + x_num * y_den
lowercase__ = gcd(lowerCAmelCase_ , lowerCAmelCase_ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase__ = add_three(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
unique_s.add(lowerCAmelCase_ )
# n=2
lowercase__ = x_num * x_num * y_num * y_num
lowercase__ = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(lowerCAmelCase_ ) and is_sq(lowerCAmelCase_ ):
lowercase__ = int(sqrt(lowerCAmelCase_ ) )
lowercase__ = int(sqrt(lowerCAmelCase_ ) )
lowercase__ = gcd(lowerCAmelCase_ , lowerCAmelCase_ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
lowercase__ = add_three(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
unique_s.add(lowerCAmelCase_ )
for num, den in unique_s:
total += Fraction(lowerCAmelCase_ , lowerCAmelCase_ )
return total.denominator + total.numerator
if __name__ == "__main__":
print(F'''{solution() = }''')
| 707 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
a__ : Optional[int] = {
"configuration_blenderbot": [
"BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BlenderbotConfig",
"BlenderbotOnnxConfig",
],
"tokenization_blenderbot": ["BlenderbotTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Any = ["BlenderbotTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Dict = [
"BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlenderbotForCausalLM",
"BlenderbotForConditionalGeneration",
"BlenderbotModel",
"BlenderbotPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : List[str] = [
"TFBlenderbotForConditionalGeneration",
"TFBlenderbotModel",
"TFBlenderbotPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : int = [
"FlaxBlenderbotForConditionalGeneration",
"FlaxBlenderbotModel",
"FlaxBlenderbotPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_blenderbot import (
BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotConfig,
BlenderbotOnnxConfig,
)
from .tokenization_blenderbot import BlenderbotTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot import (
BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotForCausalLM,
BlenderbotForConditionalGeneration,
BlenderbotModel,
BlenderbotPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot import (
TFBlenderbotForConditionalGeneration,
TFBlenderbotModel,
TFBlenderbotPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
FlaxBlenderbotPreTrainedModel,
)
else:
import sys
a__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 642 | 0 |
'''simple docstring'''
def a ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Dict:
"""simple docstring"""
if n == 0:
return 1
elif n % 2 == 1:
return (binary_exponentiation(_UpperCAmelCase , n - 1 , _UpperCAmelCase ) * a) % mod
else:
a_ = binary_exponentiation(_UpperCAmelCase , n / 2 , _UpperCAmelCase )
return (b * b) % mod
# a prime number
__lowerCAmelCase =701
__lowerCAmelCase =10_0000_0000
__lowerCAmelCase =10
# using binary exponentiation function, O(log(p)):
print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p)
print((a / b) % p == (a * b ** (p - 2)) % p)
| 697 |
'''simple docstring'''
def a ( _UpperCAmelCase , _UpperCAmelCase ) -> str:
"""simple docstring"""
if not isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise ValueError('iterations must be defined as integers' )
if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or not number >= 1:
raise ValueError(
'starting number must be\n and integer and be more than 0' )
if not iterations >= 1:
raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' )
a_ = ''
while number <= iterations:
if number % 3 == 0:
out += "Fizz"
if number % 5 == 0:
out += "Buzz"
if 0 not in (number % 3, number % 5):
out += str(_UpperCAmelCase )
# print(out)
number += 1
out += " "
return out
if __name__ == "__main__":
import doctest
doctest.testmod()
| 697 | 1 |
'''simple docstring'''
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class __lowercase :
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = None
def lowerCAmelCase ( self ):
__UpperCamelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict )
__UpperCamelCase : str = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , _lowerCamelCase )
def lowerCAmelCase ( self ):
__UpperCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__UpperCamelCase : Any = os.path.join(_lowerCamelCase , 'feat_extract.json' )
feat_extract_first.to_json_file(_lowerCamelCase )
__UpperCamelCase : Optional[Any] = self.feature_extraction_class.from_json_file(_lowerCamelCase )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def lowerCAmelCase ( self ):
__UpperCamelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__UpperCamelCase : Optional[int] = feat_extract_first.save_pretrained(_lowerCamelCase )[0]
check_json_file_has_correct_format(_lowerCamelCase )
__UpperCamelCase : int = self.feature_extraction_class.from_pretrained(_lowerCamelCase )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def lowerCAmelCase ( self ):
__UpperCamelCase : Optional[Any] = self.feature_extraction_class()
self.assertIsNotNone(_lowerCamelCase )
| 287 | '''simple docstring'''
import json
from typing import TYPE_CHECKING, List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_blenderbot import BlenderbotTokenizer
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
a= logging.get_logger(__name__)
a= {
'''vocab_file''': '''vocab.json''',
'''merges_file''': '''merges.txt''',
'''tokenizer_config_file''': '''tokenizer_config.json''',
}
a= {
'''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''},
'''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''},
'''tokenizer_config_file''': {
'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json'''
},
}
a= {'''facebook/blenderbot-3B''': 1_2_8}
class __lowercase ( _lowerCamelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE__ = ['''input_ids''', '''attention_mask''']
SCREAMING_SNAKE_CASE__ = BlenderbotTokenizer
def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="replace" , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase=False , _lowerCamelCase=True , **_lowerCamelCase , ):
super().__init__(
_lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , errors=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , add_prefix_space=_lowerCamelCase , trim_offsets=_lowerCamelCase , **_lowerCamelCase , )
__UpperCamelCase : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('add_prefix_space' , _lowerCamelCase ) != add_prefix_space:
__UpperCamelCase : Any = getattr(_lowerCamelCase , pre_tok_state.pop('type' ) )
__UpperCamelCase : Dict = add_prefix_space
__UpperCamelCase : Optional[Any] = pre_tok_class(**_lowerCamelCase )
__UpperCamelCase : str = add_prefix_space
__UpperCamelCase : Optional[int] = 'post_processor'
__UpperCamelCase : Tuple = getattr(self.backend_tokenizer , _lowerCamelCase , _lowerCamelCase )
if tokenizer_component_instance:
__UpperCamelCase : str = 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:
__UpperCamelCase : List[Any] = tuple(state['sep'] )
if "cls" in state:
__UpperCamelCase : str = tuple(state['cls'] )
__UpperCamelCase : Tuple = False
if state.get('add_prefix_space' , _lowerCamelCase ) != add_prefix_space:
__UpperCamelCase : Dict = add_prefix_space
__UpperCamelCase : str = True
if state.get('trim_offsets' , _lowerCamelCase ) != trim_offsets:
__UpperCamelCase : int = trim_offsets
__UpperCamelCase : Any = True
if changes_to_apply:
__UpperCamelCase : Dict = getattr(_lowerCamelCase , state.pop('type' ) )
__UpperCamelCase : Any = component_class(**_lowerCamelCase )
setattr(self.backend_tokenizer , _lowerCamelCase , _lowerCamelCase )
@property
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
def lowerCAmelCase ( self ):
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 lowerCAmelCase ( self , _lowerCamelCase ):
__UpperCamelCase : int = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else value
__UpperCamelCase : Optional[Any] = value
def lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ):
__UpperCamelCase : Dict = kwargs.get('is_split_into_words' , _lowerCamelCase )
assert self.add_prefix_space or not is_split_into_words, (
f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*_lowerCamelCase , **_lowerCamelCase )
def lowerCAmelCase ( self , *_lowerCamelCase , **_lowerCamelCase ):
__UpperCamelCase : Dict = kwargs.get('is_split_into_words' , _lowerCamelCase )
assert self.add_prefix_space or not is_split_into_words, (
f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._encode_plus(*_lowerCamelCase , **_lowerCamelCase )
def lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ):
__UpperCamelCase : List[str] = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase )
return tuple(_lowerCamelCase )
def lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ):
__UpperCamelCase : Union[str, Any] = [self.sep_token_id]
__UpperCamelCase : List[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase = None ):
return token_ids_a + [self.eos_token_id]
def lowerCAmelCase ( self , _lowerCamelCase ):
__UpperCamelCase : List[str] = []
for is_user, text in conversation.iter_texts():
if is_user:
# We need to space prefix as it's being done within blenderbot
inputs.append(' ' + text )
else:
# Generated responses should contain them already.
inputs.append(_lowerCamelCase )
__UpperCamelCase : Union[str, Any] = ' '.join(_lowerCamelCase )
__UpperCamelCase : Union[str, Any] = self.encode(_lowerCamelCase )
if len(_lowerCamelCase ) > self.model_max_length:
__UpperCamelCase : Tuple = input_ids[-self.model_max_length :]
logger.warning(f"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" )
return input_ids
| 287 | 1 |
'''simple docstring'''
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
lowerCAmelCase : Dict = _symbol_database.Default()
lowerCAmelCase : Union[str, Any] = _descriptor_pool.Default().AddSerializedFile(
B'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
)
lowerCAmelCase : Optional[Any] = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
lowerCAmelCase : Optional[int] = None
lowerCAmelCase : str = B'H\003'
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
lowerCAmelCase : Optional[int] = 45
lowerCAmelCase : Tuple = 15_81
lowerCAmelCase : Tuple = 15_17
lowerCAmelCase : Tuple = 15_70
lowerCAmelCase : Union[str, Any] = 15_84
lowerCAmelCase : Optional[int] = 17_93
lowerCAmelCase : int = 17_95
lowerCAmelCase : Dict = 19_16
lowerCAmelCase : List[Any] = 18_64
lowerCAmelCase : Any = 19_05
lowerCAmelCase : Any = 19_19
lowerCAmelCase : str = 24_29
lowerCAmelCase : str = 22_08
lowerCAmelCase : Any = 24_18
lowerCAmelCase : Dict = 23_23
lowerCAmelCase : Optional[int] = 24_07
# @@protoc_insertion_point(module_scope)
| 3 |
"""simple docstring"""
from diffusers.utils.testing_utils import require_onnxruntime
@require_onnxruntime
class lowerCAmelCase__ :
'''simple docstring'''
pass | 630 | 0 |
"""simple docstring"""
import argparse
A_ = "docs/source/_static/js/custom.js"
def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Dict:
with open(UpperCAmelCase__, encoding="""utf-8""", newline="""\n""" ) as f:
A__ : Optional[int] = f.readlines()
A__ : Tuple = 0
# First let's put the right version
while not lines[index].startswith("""const stableVersion =""" ):
index += 1
A__ : Optional[Any] = f'const stableVersion = "v{version}"\n'
# Then update the dictionary
while not lines[index].startswith("""const versionMapping = {""" ):
index += 1
# We go until the end
while not lines[index].startswith("""}""" ):
index += 1
# We add the new version at the end
lines[index - 1] += f' "v{version}": "v{version}",\n'
with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f:
f.writelines(UpperCAmelCase__ )
if __name__ == "__main__":
A_ = argparse.ArgumentParser()
parser.add_argument('''--version''', help='''Release version.''')
A_ = parser.parse_args()
update_custom_js(args.version)
| 708 |
"""simple docstring"""
from .integrations import (
is_optuna_available,
is_ray_available,
is_sigopt_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
run_hp_search_sigopt,
run_hp_search_wandb,
)
from .trainer_utils import (
HPSearchBackend,
default_hp_space_optuna,
default_hp_space_ray,
default_hp_space_sigopt,
default_hp_space_wandb,
)
from .utils import logging
A_ = logging.get_logger(__name__)
class __SCREAMING_SNAKE_CASE :
snake_case_ = 42
snake_case_ = None
@staticmethod
def _UpperCamelCase ( ):
'''simple docstring'''
raise NotImplementedError
def _UpperCamelCase ( self : str , snake_case : int , snake_case : int , snake_case : str , **snake_case : Any ):
'''simple docstring'''
raise NotImplementedError
def _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[int] ):
'''simple docstring'''
raise NotImplementedError
def _UpperCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
if not self.is_available():
raise RuntimeError(
F'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' )
@classmethod
def _UpperCamelCase ( cls : Optional[int] ):
'''simple docstring'''
return F'`pip install {cls.pip_package or cls.name}`'
class __SCREAMING_SNAKE_CASE ( UpperCamelCase ):
snake_case_ = 'optuna'
@staticmethod
def _UpperCamelCase ( ):
'''simple docstring'''
return is_optuna_available()
def _UpperCamelCase ( self : str , snake_case : str , snake_case : int , snake_case : str , **snake_case : Any ):
'''simple docstring'''
return run_hp_search_optuna(snake_case , snake_case , snake_case , **snake_case )
def _UpperCamelCase ( self : Optional[Any] , snake_case : int ):
'''simple docstring'''
return default_hp_space_optuna(snake_case )
class __SCREAMING_SNAKE_CASE ( UpperCamelCase ):
snake_case_ = 'ray'
snake_case_ = '\'ray[tune]\''
@staticmethod
def _UpperCamelCase ( ):
'''simple docstring'''
return is_ray_available()
def _UpperCamelCase ( self : Any , snake_case : Tuple , snake_case : int , snake_case : str , **snake_case : List[Any] ):
'''simple docstring'''
return run_hp_search_ray(snake_case , snake_case , snake_case , **snake_case )
def _UpperCamelCase ( self : Dict , snake_case : Dict ):
'''simple docstring'''
return default_hp_space_ray(snake_case )
class __SCREAMING_SNAKE_CASE ( UpperCamelCase ):
snake_case_ = 'sigopt'
@staticmethod
def _UpperCamelCase ( ):
'''simple docstring'''
return is_sigopt_available()
def _UpperCamelCase ( self : str , snake_case : str , snake_case : int , snake_case : str , **snake_case : Union[str, Any] ):
'''simple docstring'''
return run_hp_search_sigopt(snake_case , snake_case , snake_case , **snake_case )
def _UpperCamelCase ( self : List[str] , snake_case : Any ):
'''simple docstring'''
return default_hp_space_sigopt(snake_case )
class __SCREAMING_SNAKE_CASE ( UpperCamelCase ):
snake_case_ = 'wandb'
@staticmethod
def _UpperCamelCase ( ):
'''simple docstring'''
return is_wandb_available()
def _UpperCamelCase ( self : int , snake_case : int , snake_case : int , snake_case : str , **snake_case : Any ):
'''simple docstring'''
return run_hp_search_wandb(snake_case , snake_case , snake_case , **snake_case )
def _UpperCamelCase ( self : Optional[int] , snake_case : Union[str, Any] ):
'''simple docstring'''
return default_hp_space_wandb(snake_case )
A_ = {
HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}
def _lowerCAmelCase ( ) ->str:
A__ : List[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
if len(UpperCAmelCase__ ) > 0:
A__ : Dict = available_backends[0].name
if len(UpperCAmelCase__ ) > 1:
logger.info(
f'{len(UpperCAmelCase__ )} hyperparameter search backends available. Using {name} as the default.' )
return name
raise RuntimeError(
"""No hyperparameter search backend available.\n"""
+ """\n""".join(
f' - To install {backend.name} run {backend.pip_install()}'
for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
| 498 | 0 |
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
_lowerCamelCase : Optional[int] = pytest.mark.integration
@pytest.mark.parametrize('''path''' , ['''paws''', '''csv'''] )
def A__ ( __A : Any , __A : Optional[Any] ) ->Dict:
inspect_dataset(__A , __A )
__A =path + '''.py'''
assert script_name in os.listdir(__A )
assert "__pycache__" not in os.listdir(__A )
@pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' )
@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' )
@pytest.mark.parametrize('''path''' , ['''accuracy'''] )
def A__ ( __A : List[Any] , __A : Optional[Any] ) ->Optional[Any]:
inspect_metric(__A , __A )
__A =path + '''.py'''
assert script_name in os.listdir(__A )
assert "__pycache__" not in os.listdir(__A )
@pytest.mark.parametrize(
'''path, config_name, expected_splits''' , [
('''squad''', '''plain_text''', ['''train''', '''validation''']),
('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']),
('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']),
] , )
def A__ ( __A : Any , __A : Union[str, Any] , __A : Union[str, Any] ) ->Union[str, Any]:
__A =get_dataset_config_info(__A , config_name=__A )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'''path, config_name, expected_exception''' , [
('''paws''', None, ValueError),
] , )
def A__ ( __A : Any , __A : Tuple , __A : Dict ) ->Tuple:
with pytest.raises(__A ):
get_dataset_config_info(__A , config_name=__A )
@pytest.mark.parametrize(
'''path, expected''' , [
('''squad''', '''plain_text'''),
('''acronym_identification''', '''default'''),
('''lhoestq/squad''', '''plain_text'''),
('''lhoestq/test''', '''default'''),
('''lhoestq/demo1''', '''lhoestq--demo1'''),
('''dalle-mini/wit''', '''dalle-mini--wit'''),
] , )
def A__ ( __A : List[str] , __A : Any ) ->Any:
__A =get_dataset_config_names(__A )
assert expected in config_names
@pytest.mark.parametrize(
'''path, expected_configs, expected_splits_in_first_config''' , [
('''squad''', ['''plain_text'''], ['''train''', '''validation''']),
('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']),
('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']),
] , )
def A__ ( __A : List[Any] , __A : Tuple , __A : int ) ->Optional[Any]:
__A =get_dataset_infos(__A )
assert list(infos.keys() ) == expected_configs
__A =expected_configs[0]
assert expected_config in infos
__A =infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits_in_first_config
@pytest.mark.parametrize(
'''path, expected_config, expected_splits''' , [
('''squad''', '''plain_text''', ['''train''', '''validation''']),
('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']),
('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']),
] , )
def A__ ( __A : List[str] , __A : Optional[int] , __A : Any ) ->Dict:
__A =get_dataset_infos(__A )
assert expected_config in infos
__A =infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
'''path, config_name, expected_exception''' , [
('''paws''', None, ValueError),
] , )
def A__ ( __A : Any , __A : Dict , __A : str ) ->List[str]:
with pytest.raises(__A ):
get_dataset_split_names(__A , config_name=__A )
| 184 |
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
_lowerCamelCase : List[Any] = logging.getLogger(__name__)
class lowerCAmelCase__ ( __magic_name__ ):
'''simple docstring'''
def __init__( self , lowercase__=-1 ):
'''simple docstring'''
__A =label_idx
def __UpperCamelCase ( self , lowercase__ , lowercase__ ):
'''simple docstring'''
if isinstance(lowercase__ , lowercase__ ):
__A =mode.value
__A =os.path.join(lowercase__ , f'''{mode}.txt''' )
__A =1
__A =[]
with open(lowercase__ , encoding='''utf-8''' ) as f:
__A =[]
__A =[]
for line in f:
if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=lowercase__ , labels=lowercase__ ) )
guid_index += 1
__A =[]
__A =[]
else:
__A =line.split(''' ''' )
words.append(splits[0] )
if len(lowercase__ ) > 1:
labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) )
else:
# Examples could have no label for mode = "test"
labels.append('''O''' )
if words:
examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=lowercase__ , labels=lowercase__ ) )
return examples
def __UpperCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
__A =0
for line in test_input_reader:
if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n":
writer.write(lowercase__ )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
__A =line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n'''
writer.write(lowercase__ )
else:
logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] )
def __UpperCamelCase ( self , lowercase__ ):
'''simple docstring'''
if path:
with open(lowercase__ , '''r''' ) as f:
__A =f.read().splitlines()
if "O" not in labels:
__A =['''O'''] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class lowerCAmelCase__ ( __magic_name__ ):
'''simple docstring'''
def __init__( self ):
'''simple docstring'''
super().__init__(label_idx=-2 )
def __UpperCamelCase ( self , lowercase__ ):
'''simple docstring'''
if path:
with open(lowercase__ , '''r''' ) as f:
__A =f.read().splitlines()
if "O" not in labels:
__A =['''O'''] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class lowerCAmelCase__ ( __magic_name__ ):
'''simple docstring'''
def __UpperCamelCase ( self , lowercase__ , lowercase__ ):
'''simple docstring'''
if isinstance(lowercase__ , lowercase__ ):
__A =mode.value
__A =os.path.join(lowercase__ , f'''{mode}.txt''' )
__A =1
__A =[]
with open(lowercase__ , encoding='''utf-8''' ) as f:
for sentence in parse_incr(lowercase__ ):
__A =[]
__A =[]
for token in sentence:
words.append(token['''form'''] )
labels.append(token['''upos'''] )
assert len(lowercase__ ) == len(lowercase__ )
if words:
examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=lowercase__ , labels=lowercase__ ) )
guid_index += 1
return examples
def __UpperCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
__A =0
for sentence in parse_incr(lowercase__ ):
__A =preds_list[example_id]
__A =''''''
for token in sentence:
out += f'''{token['form']} ({token['upos']}|{s_p.pop(0 )}) '''
out += "\n"
writer.write(lowercase__ )
example_id += 1
def __UpperCamelCase ( self , lowercase__ ):
'''simple docstring'''
if path:
with open(lowercase__ , '''r''' ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 184 | 1 |
from collections.abc import Callable
class lowercase_ :
def __init__( self: int, _lowercase: Callable | None = None):
'''simple docstring'''
__lowerCAmelCase = []
# Stores indexes of each item for supporting updates and deletion.
__lowerCAmelCase = {}
# Stores current size of heap.
__lowerCAmelCase = 0
# Stores function used to evaluate the score of an item on which basis ordering
# will be done.
__lowerCAmelCase = key or (lambda _lowercase: x)
def _lowercase ( self: Tuple, _lowercase: int):
'''simple docstring'''
return int((i - 1) / 2) if i > 0 else None
def _lowercase ( self: List[str], _lowercase: int):
'''simple docstring'''
__lowerCAmelCase = int(2 * i + 1)
return left if 0 < left < self.size else None
def _lowercase ( self: Tuple, _lowercase: int):
'''simple docstring'''
__lowerCAmelCase = int(2 * i + 2)
return right if 0 < right < self.size else None
def _lowercase ( self: Optional[Any], _lowercase: int, _lowercase: int):
'''simple docstring'''
__lowerCAmelCase , __lowerCAmelCase = (
self.pos_map[self.arr[j][0]],
self.pos_map[self.arr[i][0]],
)
# Then swap the items in the list.
__lowerCAmelCase , __lowerCAmelCase = self.arr[j], self.arr[i]
def _lowercase ( self: Optional[int], _lowercase: int, _lowercase: int):
'''simple docstring'''
return self.arr[i][1] < self.arr[j][1]
def _lowercase ( self: Dict, _lowercase: int):
'''simple docstring'''
__lowerCAmelCase = self._left(_lowercase)
__lowerCAmelCase = self._right(_lowercase)
__lowerCAmelCase = i
if left is not None and not self._cmp(_lowercase, _lowercase):
__lowerCAmelCase = left
if right is not None and not self._cmp(_lowercase, _lowercase):
__lowerCAmelCase = right
return valid_parent
def _lowercase ( self: Union[str, Any], _lowercase: int):
'''simple docstring'''
__lowerCAmelCase = self._parent(_lowercase)
while parent is not None and not self._cmp(_lowercase, _lowercase):
self._swap(_lowercase, _lowercase)
__lowerCAmelCase , __lowerCAmelCase = parent, self._parent(_lowercase)
def _lowercase ( self: Union[str, Any], _lowercase: int):
'''simple docstring'''
__lowerCAmelCase = self._get_valid_parent(_lowercase)
while valid_parent != index:
self._swap(_lowercase, _lowercase)
__lowerCAmelCase , __lowerCAmelCase = valid_parent, self._get_valid_parent(_lowercase)
def _lowercase ( self: Optional[Any], _lowercase: int, _lowercase: int):
'''simple docstring'''
if item not in self.pos_map:
return
__lowerCAmelCase = self.pos_map[item]
__lowerCAmelCase = [item, self.key(_lowercase)]
# Make sure heap is right in both up and down direction.
# Ideally only one of them will make any change.
self._heapify_up(_lowercase)
self._heapify_down(_lowercase)
def _lowercase ( self: Optional[int], _lowercase: int):
'''simple docstring'''
if item not in self.pos_map:
return
__lowerCAmelCase = self.pos_map[item]
del self.pos_map[item]
__lowerCAmelCase = self.arr[self.size - 1]
__lowerCAmelCase = index
self.size -= 1
# Make sure heap is right in both up and down direction. Ideally only one
# of them will make any change- so no performance loss in calling both.
if self.size > index:
self._heapify_up(_lowercase)
self._heapify_down(_lowercase)
def _lowercase ( self: List[Any], _lowercase: int, _lowercase: int):
'''simple docstring'''
__lowerCAmelCase = len(self.arr)
if arr_len == self.size:
self.arr.append([item, self.key(_lowercase)])
else:
__lowerCAmelCase = [item, self.key(_lowercase)]
__lowerCAmelCase = self.size
self.size += 1
self._heapify_up(self.size - 1)
def _lowercase ( self: List[str]):
'''simple docstring'''
return self.arr[0] if self.size else None
def _lowercase ( self: Optional[int]):
'''simple docstring'''
__lowerCAmelCase = self.get_top()
if top_item_tuple:
self.delete_item(top_item_tuple[0])
return top_item_tuple
def UpperCAmelCase ( ) -> None:
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 334 |
import argparse
import json
import os
import torch
from transformers.file_utils import has_file
from diffusers import UNetaDConditionModel, UNetaDModel
__A : Tuple = False
__A : Optional[int] = True
__A : Optional[Any] = False
if __name__ == "__main__":
__A : Any = argparse.ArgumentParser()
parser.add_argument(
"--repo_path",
default=None,
type=str,
required=True,
help="The config json file corresponding to the architecture.",
)
parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
__A : List[str] = parser.parse_args()
__A : List[Any] = {
"image_size": "sample_size",
"num_res_blocks": "layers_per_block",
"block_channels": "block_out_channels",
"down_blocks": "down_block_types",
"up_blocks": "up_block_types",
"downscale_freq_shift": "freq_shift",
"resnet_num_groups": "norm_num_groups",
"resnet_act_fn": "act_fn",
"resnet_eps": "norm_eps",
"num_head_channels": "attention_head_dim",
}
__A : Optional[int] = {
"time_steps": "time_proj",
"mid": "mid_block",
"downsample_blocks": "down_blocks",
"upsample_blocks": "up_blocks",
}
__A : List[str] = "" if has_file(args.repo_path, "config.json") else "unet"
with open(os.path.join(args.repo_path, subfolder, "config.json"), "r", encoding="utf-8") as reader:
__A : List[str] = reader.read()
__A : int = json.loads(text)
if do_only_config:
for key in config_parameters_to_change.keys():
config.pop(key, None)
if has_file(args.repo_path, "config.json"):
__A : List[str] = UNetaDModel(**config)
else:
__A : Dict = UNetaDConditionModel if "ldm-text2im-large-256" in args.repo_path else UNetaDModel
__A : Optional[int] = class_name(**config)
if do_only_config:
model.save_config(os.path.join(args.repo_path, subfolder))
__A : List[Any] = dict(model.config)
if do_only_renaming:
for key, value in config_parameters_to_change.items():
if key in config:
__A : Optional[Any] = config[key]
del config[key]
__A : Dict = [k.replace("UNetRes", "") for k in config["down_block_types"]]
__A : Tuple = [k.replace("UNetRes", "") for k in config["up_block_types"]]
if do_only_weights:
__A : Dict = torch.load(os.path.join(args.repo_path, subfolder, "diffusion_pytorch_model.bin"))
__A : Tuple = {}
for param_key, param_value in state_dict.items():
if param_key.endswith(".op.bias") or param_key.endswith(".op.weight"):
continue
__A : Dict = False
for key, new_key in key_parameters_to_change.items():
if not has_changed and param_key.split(".")[0] == key:
__A : List[Any] = param_value
__A : Optional[Any] = True
if not has_changed:
__A : List[Any] = param_value
model.load_state_dict(new_state_dict)
model.save_pretrained(os.path.join(args.repo_path, subfolder))
| 334 | 1 |
"""simple docstring"""
import sys
import webbrowser
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print('''Googling.....''')
_SCREAMING_SNAKE_CASE : Optional[int] = '''https://www.google.com/search?q=''' + ''' '''.join(sys.argv[1:])
_SCREAMING_SNAKE_CASE : Any = requests.get(url, headers={'''UserAgent''': UserAgent().random})
# res.raise_for_status()
with open('''project1a.html''', '''wb''') as out_file: # only for knowing the class
for data in res.iter_content(1_0000):
out_file.write(data)
_SCREAMING_SNAKE_CASE : Any = BeautifulSoup(res.text, '''html.parser''')
_SCREAMING_SNAKE_CASE : int = list(soup.select('''.eZt8xd'''))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get('''href'''))
else:
webbrowser.open(F'''https://google.com{link.get('href')}''')
| 549 |
"""simple docstring"""
import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple
import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader
from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
ROUGE_KEYS,
LegacySeqaSeqDataset,
SeqaSeqDataset,
assert_all_frozen,
calculate_bleu,
calculate_rouge,
check_output_dir,
flatten_list,
freeze_embeds,
freeze_params,
get_git_info,
label_smoothed_nll_loss,
lmap,
pickle_save,
save_git_info,
save_json,
use_task_specific_params,
)
# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa
_SCREAMING_SNAKE_CASE : str = logging.getLogger(__name__)
class a ( __snake_case ):
SCREAMING_SNAKE_CASE : Optional[Any] = """summarization"""
SCREAMING_SNAKE_CASE : Any = ["""loss"""]
SCREAMING_SNAKE_CASE : Optional[int] = ROUGE_KEYS
SCREAMING_SNAKE_CASE : Optional[int] = """rouge2"""
def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[str] , **__SCREAMING_SNAKE_CASE : List[str] ) -> Union[str, Any]:
if hparams.sortish_sampler and hparams.gpus > 1:
lowerCamelCase_ = False
elif hparams.max_tokens_per_batch is not None:
if hparams.gpus > 1:
raise NotImplementedError('Dynamic Batch size does not work for multi-gpu training' )
if hparams.sortish_sampler:
raise ValueError('--sortish_sampler and --max_tokens_per_batch may not be used simultaneously' )
super().__init__(__SCREAMING_SNAKE_CASE , num_labels=__SCREAMING_SNAKE_CASE , mode=self.mode , **__SCREAMING_SNAKE_CASE )
use_task_specific_params(self.model , 'summarization' )
save_git_info(self.hparams.output_dir )
lowerCamelCase_ = Path(self.output_dir ) / 'metrics.json'
lowerCamelCase_ = Path(self.output_dir ) / 'hparams.pkl'
pickle_save(self.hparams , self.hparams_save_path )
lowerCamelCase_ = 0
lowerCamelCase_ = defaultdict(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = self.config.model_type
lowerCamelCase_ = self.config.tgt_vocab_size if self.model_type == 'fsmt' else self.config.vocab_size
lowerCamelCase_ = {
"data_dir": self.hparams.data_dir,
"max_source_length": self.hparams.max_source_length,
"prefix": self.model.config.prefix or "",
}
lowerCamelCase_ = {
'train': self.hparams.n_train,
'val': self.hparams.n_val,
'test': self.hparams.n_test,
}
lowerCamelCase_ = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}
lowerCamelCase_ = {
'train': self.hparams.max_target_length,
'val': self.hparams.val_max_target_length,
'test': self.hparams.test_max_target_length,
}
assert self.target_lens["train"] <= self.target_lens["val"], F'''target_lens: {self.target_lens}'''
assert self.target_lens["train"] <= self.target_lens["test"], F'''target_lens: {self.target_lens}'''
if self.hparams.freeze_embeds:
freeze_embeds(self.model )
if self.hparams.freeze_encoder:
freeze_params(self.model.get_encoder() )
assert_all_frozen(self.model.get_encoder() )
lowerCamelCase_ = get_git_info()['repo_sha']
lowerCamelCase_ = hparams.num_workers
lowerCamelCase_ = None # default to config
if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE ):
lowerCamelCase_ = self.tokenizer.lang_code_to_id[hparams.tgt_lang]
lowerCamelCase_ = self.decoder_start_token_id
lowerCamelCase_ = (
SeqaSeqDataset if hasattr(self.tokenizer , 'prepare_seq2seq_batch' ) else LegacySeqaSeqDataset
)
lowerCamelCase_ = False
lowerCamelCase_ = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
if self.hparams.eval_max_gen_length is not None:
lowerCamelCase_ = self.hparams.eval_max_gen_length
else:
lowerCamelCase_ = self.model.config.max_length
lowerCamelCase_ = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric
def UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : Dict[str, torch.Tensor] ) -> Dict[str, List[str]]:
lowerCamelCase_ = {
k: self.tokenizer.batch_decode(v.tolist() ) if 'mask' not in k else v.shape for k, v in batch.items()
}
save_json(__SCREAMING_SNAKE_CASE , Path(self.output_dir ) / 'text_batch.json' )
save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir ) / 'tok_batch.json' )
lowerCamelCase_ = True
return readable_batch
def UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : int , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Any:
return self.model(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[int] ) -> int:
lowerCamelCase_ = self.tokenizer.batch_decode(
__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE )
return lmap(str.strip , __SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : dict ) -> Tuple:
lowerCamelCase_ = self.tokenizer.pad_token_id
lowerCamelCase_ , lowerCamelCase_ = batch['input_ids'], batch['attention_mask']
lowerCamelCase_ = batch['labels']
if isinstance(self.model , __SCREAMING_SNAKE_CASE ):
lowerCamelCase_ = self.model._shift_right(__SCREAMING_SNAKE_CASE )
else:
lowerCamelCase_ = shift_tokens_right(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero
lowerCamelCase_ = decoder_input_ids
self.save_readable_batch(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = self(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = outputs['logits']
if self.hparams.label_smoothing == 0:
# Same behavior as modeling_bart.py, besides ignoring pad_token_id
lowerCamelCase_ = nn.CrossEntropyLoss(ignore_index=__SCREAMING_SNAKE_CASE )
assert lm_logits.shape[-1] == self.vocab_size
lowerCamelCase_ = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1] ) , tgt_ids.view(-1 ) )
else:
lowerCamelCase_ = nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1 )
lowerCamelCase_ , lowerCamelCase_ = label_smoothed_nll_loss(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.hparams.label_smoothing , ignore_index=__SCREAMING_SNAKE_CASE )
return (loss,)
@property
def UpperCamelCase ( self : Optional[Any] ) -> int:
return self.tokenizer.pad_token_id
def UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Any ) -> Dict:
lowerCamelCase_ = self._step(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = dict(zip(self.loss_names , __SCREAMING_SNAKE_CASE ) )
# tokens per batch
lowerCamelCase_ = batch['input_ids'].ne(self.pad ).sum() + batch['labels'].ne(self.pad ).sum()
lowerCamelCase_ = batch['input_ids'].shape[0]
lowerCamelCase_ = batch['input_ids'].eq(self.pad ).sum()
lowerCamelCase_ = batch['input_ids'].eq(self.pad ).float().mean()
# TODO(SS): make a wandb summary metric for this
return {"loss": loss_tensors[0], "log": logs}
def UpperCamelCase ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int ) -> Dict:
return self._generative_step(__SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : str , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]="val" ) -> Dict:
self.step_count += 1
lowerCamelCase_ = {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names}
lowerCamelCase_ = losses['loss']
lowerCamelCase_ = {
k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ['gen_time', 'gen_len']
}
lowerCamelCase_ = (
generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
)
lowerCamelCase_ = torch.tensor(__SCREAMING_SNAKE_CASE ).type_as(__SCREAMING_SNAKE_CASE )
generative_metrics.update({k: v.item() for k, v in losses.items()} )
losses.update(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = {F'''{prefix}_avg_{k}''': x for k, x in losses.items()}
lowerCamelCase_ = self.step_count
self.metrics[prefix].append(__SCREAMING_SNAKE_CASE ) # callback writes this to self.metrics_save_path
lowerCamelCase_ = flatten_list([x['preds'] for x in outputs] )
return {
"log": all_metrics,
"preds": preds,
F'''{prefix}_loss''': loss,
F'''{prefix}_{self.val_metric}''': metric_tensor,
}
def UpperCamelCase ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] ) -> Dict:
return calculate_rouge(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : List[str] , __SCREAMING_SNAKE_CASE : dict ) -> dict:
lowerCamelCase_ = time.time()
# parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
lowerCamelCase_ = self.model.generate(
batch['input_ids'] , attention_mask=batch['attention_mask'] , use_cache=__SCREAMING_SNAKE_CASE , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , )
lowerCamelCase_ = (time.time() - ta) / batch['input_ids'].shape[0]
lowerCamelCase_ = self.ids_to_clean_text(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = self.ids_to_clean_text(batch['labels'] )
lowerCamelCase_ = self._step(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = dict(zip(self.loss_names , __SCREAMING_SNAKE_CASE ) )
lowerCamelCase_ = self.calc_generative_metrics(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
lowerCamelCase_ = np.mean(lmap(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )
base_metrics.update(gen_time=__SCREAMING_SNAKE_CASE , gen_len=__SCREAMING_SNAKE_CASE , preds=__SCREAMING_SNAKE_CASE , target=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
return base_metrics
def UpperCamelCase ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int ) -> Any:
return self._generative_step(__SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Tuple:
return self.validation_epoch_end(__SCREAMING_SNAKE_CASE , prefix='test' )
def UpperCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : Optional[int] ) -> SeqaSeqDataset:
lowerCamelCase_ = self.n_obs[type_path]
lowerCamelCase_ = self.target_lens[type_path]
lowerCamelCase_ = self.dataset_class(
self.tokenizer , type_path=__SCREAMING_SNAKE_CASE , n_obs=__SCREAMING_SNAKE_CASE , max_target_length=__SCREAMING_SNAKE_CASE , **self.dataset_kwargs , )
return dataset
def UpperCamelCase ( self : Tuple , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> DataLoader:
lowerCamelCase_ = self.get_dataset(__SCREAMING_SNAKE_CASE )
if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
lowerCamelCase_ = dataset.make_sortish_sampler(__SCREAMING_SNAKE_CASE , distributed=self.hparams.gpus > 1 )
return DataLoader(
__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=__SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=__SCREAMING_SNAKE_CASE , )
elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
lowerCamelCase_ = dataset.make_dynamic_sampler(
self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1 )
return DataLoader(
__SCREAMING_SNAKE_CASE , batch_sampler=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , num_workers=self.num_workers , )
else:
return DataLoader(
__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=__SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=__SCREAMING_SNAKE_CASE , )
def UpperCamelCase ( self : Dict ) -> DataLoader:
lowerCamelCase_ = self.get_dataloader('train' , batch_size=self.hparams.train_batch_size , shuffle=__SCREAMING_SNAKE_CASE )
return dataloader
def UpperCamelCase ( self : int ) -> DataLoader:
return self.get_dataloader('val' , batch_size=self.hparams.eval_batch_size )
def UpperCamelCase ( self : int ) -> DataLoader:
return self.get_dataloader('test' , batch_size=self.hparams.eval_batch_size )
@staticmethod
def UpperCamelCase ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Dict:
BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
add_generic_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
parser.add_argument(
'--max_source_length' , default=1024 , type=__SCREAMING_SNAKE_CASE , help=(
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
) , )
parser.add_argument(
'--max_target_length' , default=56 , type=__SCREAMING_SNAKE_CASE , help=(
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
) , )
parser.add_argument(
'--val_max_target_length' , default=142 , type=__SCREAMING_SNAKE_CASE , help=(
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
) , )
parser.add_argument(
'--test_max_target_length' , default=142 , type=__SCREAMING_SNAKE_CASE , help=(
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
) , )
parser.add_argument('--freeze_encoder' , action='store_true' )
parser.add_argument('--freeze_embeds' , action='store_true' )
parser.add_argument('--sortish_sampler' , action='store_true' , default=__SCREAMING_SNAKE_CASE )
parser.add_argument('--overwrite_output_dir' , action='store_true' , default=__SCREAMING_SNAKE_CASE )
parser.add_argument('--max_tokens_per_batch' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE )
parser.add_argument('--logger_name' , type=__SCREAMING_SNAKE_CASE , choices=['default', 'wandb', 'wandb_shared'] , default='default' )
parser.add_argument('--n_train' , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help='# examples. -1 means use all.' )
parser.add_argument('--n_val' , type=__SCREAMING_SNAKE_CASE , default=500 , required=__SCREAMING_SNAKE_CASE , help='# examples. -1 means use all.' )
parser.add_argument('--n_test' , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help='# examples. -1 means use all.' )
parser.add_argument(
'--task' , type=__SCREAMING_SNAKE_CASE , default='summarization' , required=__SCREAMING_SNAKE_CASE , help='# examples. -1 means use all.' )
parser.add_argument('--label_smoothing' , type=__SCREAMING_SNAKE_CASE , default=0.0 , required=__SCREAMING_SNAKE_CASE )
parser.add_argument('--src_lang' , type=__SCREAMING_SNAKE_CASE , default='' , required=__SCREAMING_SNAKE_CASE )
parser.add_argument('--tgt_lang' , type=__SCREAMING_SNAKE_CASE , default='' , required=__SCREAMING_SNAKE_CASE )
parser.add_argument('--eval_beams' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE )
parser.add_argument(
'--val_metric' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , choices=['bleu', 'rouge2', 'loss', None] )
parser.add_argument('--eval_max_gen_length' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help='never generate more than n tokens' )
parser.add_argument('--save_top_k' , type=__SCREAMING_SNAKE_CASE , default=1 , required=__SCREAMING_SNAKE_CASE , help='How many checkpoints to save' )
parser.add_argument(
'--early_stopping_patience' , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help=(
'-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So'
' val_check_interval will effect it.'
) , )
return parser
class a ( __snake_case ):
SCREAMING_SNAKE_CASE : Union[str, Any] = """translation"""
SCREAMING_SNAKE_CASE : List[str] = ["""loss"""]
SCREAMING_SNAKE_CASE : str = ["""bleu"""]
SCREAMING_SNAKE_CASE : Optional[int] = """bleu"""
def __init__( self : str , __SCREAMING_SNAKE_CASE : Dict , **__SCREAMING_SNAKE_CASE : Tuple ) -> Optional[Any]:
super().__init__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = hparams.src_lang
lowerCamelCase_ = hparams.tgt_lang
def UpperCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[str] ) -> dict:
return calculate_bleu(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
def lowerCamelCase__ ( _lowerCamelCase : str , _lowerCamelCase : Tuple=None ) -> SummarizationModule:
Path(args.output_dir ).mkdir(exist_ok=_lowerCamelCase )
check_output_dir(_lowerCamelCase , expected_items=3 )
if model is None:
if "summarization" in args.task:
lowerCamelCase_ = SummarizationModule(_lowerCamelCase )
else:
lowerCamelCase_ = TranslationModule(_lowerCamelCase )
lowerCamelCase_ = Path(args.data_dir ).name
if (
args.logger_name == "default"
or args.fast_dev_run
or str(args.output_dir ).startswith('/tmp' )
or str(args.output_dir ).startswith('/var' )
):
lowerCamelCase_ = True # don't pollute wandb logs unnecessarily
elif args.logger_name == "wandb":
from pytorch_lightning.loggers import WandbLogger
lowerCamelCase_ = os.environ.get('WANDB_PROJECT' , _lowerCamelCase )
lowerCamelCase_ = WandbLogger(name=model.output_dir.name , project=_lowerCamelCase )
elif args.logger_name == "wandb_shared":
from pytorch_lightning.loggers import WandbLogger
lowerCamelCase_ = WandbLogger(name=model.output_dir.name , project=F'''hf_{dataset}''' )
if args.early_stopping_patience >= 0:
lowerCamelCase_ = get_early_stopping_callback(model.val_metric , args.early_stopping_patience )
else:
lowerCamelCase_ = False
lowerCamelCase_ = args.val_metric == 'loss'
lowerCamelCase_ = generic_train(
_lowerCamelCase , _lowerCamelCase , logging_callback=SeqaSeqLoggingCallback() , checkpoint_callback=get_checkpoint_callback(
args.output_dir , model.val_metric , args.save_top_k , _lowerCamelCase ) , early_stopping_callback=_lowerCamelCase , logger=_lowerCamelCase , )
pickle_save(model.hparams , model.output_dir / 'hparams.pkl' )
if not args.do_predict:
return model
lowerCamelCase_ = ''
lowerCamelCase_ = sorted(glob.glob(os.path.join(args.output_dir , '*.ckpt' ) , recursive=_lowerCamelCase ) )
if checkpoints:
lowerCamelCase_ = checkpoints[-1]
lowerCamelCase_ = checkpoints[-1]
trainer.logger.log_hyperparams(model.hparams )
# test() without a model tests using the best checkpoint automatically
trainer.test()
return model
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser()
_SCREAMING_SNAKE_CASE : Any = pl.Trainer.add_argparse_args(parser)
_SCREAMING_SNAKE_CASE : Any = SummarizationModule.add_model_specific_args(parser, os.getcwd())
_SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args()
main(args)
| 549 | 1 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase__ : int = logging.get_logger(__name__)
lowerCAmelCase__ : Tuple = {
"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"""
SCREAMING_SNAKE_CASE = '''dpr'''
def __init__( self : Optional[int] , UpperCAmelCase_ : int=30_522 , UpperCAmelCase_ : Union[str, Any]=768 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : List[str]=12 , UpperCAmelCase_ : Dict=3_072 , UpperCAmelCase_ : Any="gelu" , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : Tuple=512 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : int=1e-12 , UpperCAmelCase_ : Union[str, Any]=0 , UpperCAmelCase_ : List[Any]="absolute" , UpperCAmelCase_ : int = 0 , **UpperCAmelCase_ : List[str] , ):
"""simple docstring"""
super().__init__(pad_token_id=UpperCAmelCase_ , **UpperCAmelCase_ )
__UpperCAmelCase : List[Any] = vocab_size
__UpperCAmelCase : int = hidden_size
__UpperCAmelCase : Optional[int] = num_hidden_layers
__UpperCAmelCase : str = num_attention_heads
__UpperCAmelCase : Optional[Any] = hidden_act
__UpperCAmelCase : List[Any] = intermediate_size
__UpperCAmelCase : List[Any] = hidden_dropout_prob
__UpperCAmelCase : Optional[Any] = attention_probs_dropout_prob
__UpperCAmelCase : int = max_position_embeddings
__UpperCAmelCase : Tuple = type_vocab_size
__UpperCAmelCase : Optional[int] = initializer_range
__UpperCAmelCase : List[Any] = layer_norm_eps
__UpperCAmelCase : str = projection_dim
__UpperCAmelCase : int = position_embedding_type
| 712 |
'''simple docstring'''
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
lowerCAmelCase__ : List[str] = TypeVar("KEY")
lowerCAmelCase__ : str = TypeVar("VAL")
@dataclass(frozen=snake_case__ ,slots=snake_case__ )
class SCREAMING_SNAKE_CASE__ ( Generic[KEY, VAL] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = 42
SCREAMING_SNAKE_CASE = 42
class SCREAMING_SNAKE_CASE__ ( _Item ):
"""simple docstring"""
def __init__( self : Tuple ):
"""simple docstring"""
super().__init__(UpperCAmelCase_ , UpperCAmelCase_ )
def __bool__( self : Dict ):
"""simple docstring"""
return False
lowerCAmelCase__ : str = _DeletedItem()
class SCREAMING_SNAKE_CASE__ ( MutableMapping[KEY, VAL] ):
"""simple docstring"""
def __init__( self : Optional[int] , UpperCAmelCase_ : int = 8 , UpperCAmelCase_ : float = 0.75 ):
"""simple docstring"""
__UpperCAmelCase : List[Any] = initial_block_size
__UpperCAmelCase : list[_Item | None] = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
__UpperCAmelCase : int = capacity_factor
__UpperCAmelCase : int = 0
def lowerCamelCase_ ( self : str , UpperCAmelCase_ : KEY ):
"""simple docstring"""
return hash(UpperCAmelCase_ ) % len(self._buckets )
def lowerCamelCase_ ( self : Dict , UpperCAmelCase_ : int ):
"""simple docstring"""
return (ind + 1) % len(self._buckets )
def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : KEY , UpperCAmelCase_ : VAL ):
"""simple docstring"""
__UpperCAmelCase : Tuple = self._buckets[ind]
if not stored:
__UpperCAmelCase : str = _Item(UpperCAmelCase_ , UpperCAmelCase_ )
self._len += 1
return True
elif stored.key == key:
__UpperCAmelCase : List[Any] = _Item(UpperCAmelCase_ , UpperCAmelCase_ )
return True
else:
return False
def lowerCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
__UpperCAmelCase : List[Any] = len(self._buckets ) * self._capacity_factor
return len(self ) >= int(UpperCAmelCase_ )
def lowerCamelCase_ ( self : Dict ):
"""simple docstring"""
if len(self._buckets ) <= self._initial_block_size:
return False
__UpperCAmelCase : Dict = len(self._buckets ) * self._capacity_factor / 2
return len(self ) < limit
def lowerCamelCase_ ( self : int , UpperCAmelCase_ : int ):
"""simple docstring"""
__UpperCAmelCase : List[Any] = self._buckets
__UpperCAmelCase : str = [None] * new_size
__UpperCAmelCase : Any = 0
for item in old_buckets:
if item:
self._add_item(item.key , item.val )
def lowerCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
self._resize(len(self._buckets ) * 2 )
def lowerCamelCase_ ( self : int ):
"""simple docstring"""
self._resize(len(self._buckets ) // 2 )
def lowerCamelCase_ ( self : List[str] , UpperCAmelCase_ : KEY ):
"""simple docstring"""
__UpperCAmelCase : str = self._get_bucket_index(UpperCAmelCase_ )
for _ in range(len(self._buckets ) ):
yield ind
__UpperCAmelCase : Optional[Any] = self._get_next_ind(UpperCAmelCase_ )
def lowerCamelCase_ ( self : Union[str, Any] , UpperCAmelCase_ : KEY , UpperCAmelCase_ : VAL ):
"""simple docstring"""
for ind in self._iterate_buckets(UpperCAmelCase_ ):
if self._try_set(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ):
break
def __setitem__( self : Tuple , UpperCAmelCase_ : KEY , UpperCAmelCase_ : VAL ):
"""simple docstring"""
if self._is_full():
self._size_up()
self._add_item(UpperCAmelCase_ , UpperCAmelCase_ )
def __delitem__( self : Optional[int] , UpperCAmelCase_ : KEY ):
"""simple docstring"""
for ind in self._iterate_buckets(UpperCAmelCase_ ):
__UpperCAmelCase : Optional[int] = self._buckets[ind]
if item is None:
raise KeyError(UpperCAmelCase_ )
if item is _deleted:
continue
if item.key == key:
__UpperCAmelCase : Optional[Any] = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__( self : Any , UpperCAmelCase_ : KEY ):
"""simple docstring"""
for ind in self._iterate_buckets(UpperCAmelCase_ ):
__UpperCAmelCase : str = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(UpperCAmelCase_ )
def __len__( self : List[Any] ):
"""simple docstring"""
return self._len
def __iter__( self : Optional[int] ):
"""simple docstring"""
yield from (item.key for item in self._buckets if item)
def __repr__( self : List[str] ):
"""simple docstring"""
__UpperCAmelCase : Any = " ,".join(
f"{item.key}: {item.val}" for item in self._buckets if item )
return f"HashMap({val_string})"
| 329 | 0 |
'''simple docstring'''
import pytest
from datasets import inspect_metric, list_metrics, load_metric
@pytest.fixture
def _A ( A ) -> List[Any]:
monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" ,set() )
@pytest.fixture
def _A ( A ) -> Tuple:
class _UpperCamelCase :
'''simple docstring'''
def __init__( self , a_ ) -> Tuple:
lowercase : Dict = metric_id
class _UpperCamelCase :
'''simple docstring'''
_snake_case = [MetricMock(__snake_case) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]]
def a__ ( self ) -> Union[str, Any]:
return self._metrics
monkeypatch.setattr("datasets.inspect.huggingface_hub" ,HfhMock() )
@pytest.mark.parametrize(
"func, args" ,[(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] )
def _A ( A ,A ,A ,A ,A ) -> List[Any]:
if "tmp_path" in args:
lowercase : Dict = tuple(arg if arg != "tmp_path" else tmp_path for arg in args )
with pytest.warns(_A ,match="https://huggingface.co/docs/evaluate" ):
func(*_A )
| 372 |
"""simple docstring"""
import argparse
import logging
import pickle
from collections import Counter
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO
)
_lowerCAmelCase = logging.getLogger(__name__)
if __name__ == "__main__":
_lowerCAmelCase = argparse.ArgumentParser(
description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)'
)
parser.add_argument(
'--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.'
)
parser.add_argument(
'--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.'
)
parser.add_argument('--vocab_size', default=3_05_22, type=int)
_lowerCAmelCase = parser.parse_args()
logger.info(F'Loading data from {args.data_file}')
with open(args.data_file, 'rb') as fp:
_lowerCAmelCase = pickle.load(fp)
logger.info('Counting occurrences for MLM.')
_lowerCAmelCase = Counter()
for tk_ids in data:
counter.update(tk_ids)
_lowerCAmelCase = [0] * args.vocab_size
for k, v in counter.items():
_lowerCAmelCase = v
logger.info(F'Dump to {args.token_counts_dump}')
with open(args.token_counts_dump, 'wb') as handle:
pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
| 264 | 0 |
'''simple docstring'''
def __UpperCAmelCase ( __magic_name__ ,__magic_name__ )-> str:
"""simple docstring"""
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
snake_case_ : Union[str, Any] = str(bin(__magic_name__ ) )[2:] # remove the leading "0b"
snake_case_ : Optional[Any] = str(bin(__magic_name__ ) )[2:] # remove the leading "0b"
snake_case_ : Any = max(len(__magic_name__ ) ,len(__magic_name__ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(__magic_name__ ) ,b_binary.zfill(__magic_name__ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 656 |
'''simple docstring'''
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
)
from transformers.utils import is_sentencepiece_available
if is_sentencepiece_available():
from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json
from ...test_tokenization_common import TokenizerTesterMixin
if is_sentencepiece_available():
__lowerCamelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''')
if is_torch_available():
from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right
__lowerCamelCase : str = 128022
__lowerCamelCase : List[Any] = 128028
@require_sentencepiece
class A_ (a_ , unittest.TestCase ):
"""simple docstring"""
a__ = MaMaaaTokenizer
a__ = False
a__ = False
a__ = True
def _A ( self :Union[str, Any] ) -> List[str]:
'''simple docstring'''
super().setUp()
snake_case_ : int = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"]
snake_case_ : Any = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) )
snake_case_ : Optional[int] = Path(self.tmpdirname )
save_json(lowerCAmelCase__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] )
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(lowerCAmelCase__ , save_dir / VOCAB_FILES_NAMES["spm_file"] )
snake_case_ : Union[str, Any] = MaMaaaTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def _A ( self :List[Any] , **lowerCAmelCase__ :List[Any] ) -> str:
'''simple docstring'''
return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ )
def _A ( self :Optional[int] , lowerCAmelCase__ :Any ) -> Optional[int]:
'''simple docstring'''
return (
"This is a test",
"This is a test",
)
def _A ( self :List[str] ) -> Union[str, Any]:
'''simple docstring'''
snake_case_ : str = "</s>"
snake_case_ : Union[str, Any] = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) , lowerCAmelCase__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) , lowerCAmelCase__ )
def _A ( self :Union[str, Any] ) -> List[str]:
'''simple docstring'''
snake_case_ : Union[str, Any] = self.get_tokenizer()
snake_case_ : Any = list(tokenizer.get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "</s>" )
self.assertEqual(vocab_keys[1] , "<unk>" )
self.assertEqual(vocab_keys[-1] , "<s>" )
self.assertEqual(len(lowerCAmelCase__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) )
@unittest.skip("Skip this test while all models are still to be uploaded." )
def _A ( self :List[Any] ) -> Union[str, Any]:
'''simple docstring'''
pass
def _A ( self :Optional[int] ) -> int:
'''simple docstring'''
snake_case_ : int = self.get_tokenizer()
snake_case_ : List[str] = tokenizer.tokenize("This is a test" )
self.assertListEqual(lowerCAmelCase__ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , [2, 3, 4, 5, 6] , )
snake_case_ : Any = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] )
self.assertListEqual(lowerCAmelCase__ , ["▁This", "▁is", "▁a", "▁t", "est"] )
snake_case_ : Any = tokenizer.convert_tokens_to_string(lowerCAmelCase__ )
self.assertEqual(lowerCAmelCase__ , "This is a test" )
@slow
def _A ( self :Any ) -> List[Any]:
'''simple docstring'''
snake_case_ : int = {"input_ids": [[128_022, 110_108, 397, 11, 38_272, 2_247, 124_811, 285, 18_105, 1_586, 207, 7, 39_534, 4_428, 397, 1_019, 18_105, 1_586, 207, 7, 41_337, 16_786, 241, 7, 20_214, 17, 125_690, 10_398, 7, 44_378, 58_069, 68_342, 7_798, 7_343, 11, 299, 33_310, 4, 158, 37_350, 94_077, 4_569, 299, 33_310, 90, 4, 52_840, 290, 4, 31_270, 112, 299, 682, 4, 52_840, 39_953, 14_079, 193, 52_519, 90_894, 17_894, 120_697, 11, 40_445, 551, 17, 1_019, 52_519, 90_894, 17_756, 963, 11, 40_445, 480, 17, 9_792, 1_120, 5_173, 1_393, 6_240, 16_786, 241, 120_996, 28, 1_245, 1_393, 118_240, 11_123, 1_019, 93_612, 2_691, 10_618, 98_058, 120_409, 1_928, 279, 4, 40_683, 367, 178, 207, 1_019, 103, 103_121, 506, 65_296, 5, 2], [128_022, 21_217, 367, 117, 125_450, 128, 719, 7, 7_308, 40, 93_612, 12_669, 1_116, 16_704, 71, 17_785, 3_699, 15_592, 35, 144, 9_584, 241, 11_943, 713, 950, 799, 2_247, 88_427, 150, 149, 118_813, 120_706, 1_019, 106_906, 81_518, 28, 1_224, 22_799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [128_022, 1_658, 123_311, 5_155, 5_578, 4_722, 279, 14_947, 2_366, 1_120, 1_197, 14, 1_348, 9_232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowerCAmelCase__ , model_name="facebook/m2m100_418M" , revision="c168bae485c864188cf9aa0e4108b0b6934dc91e" , )
@require_torch
@require_sentencepiece
@require_tokenizers
class A_ (unittest.TestCase ):
"""simple docstring"""
a__ = '''facebook/m2m100_418M'''
a__ = [
'''In my opinion, there are two levels of response from the French government.''',
'''NSA Affair Emphasizes Complete Lack of Debate on Intelligence''',
]
a__ = [
'''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''',
'''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''',
]
# fmt: off
a__ = [EN_CODE, 593, 1949, 115781, 4, 71586, 4234, 60633, 126233, 432, 123808, 15592, 1197, 117132, 120618, 5, 2]
@classmethod
def _A ( cls :str ) -> int:
'''simple docstring'''
snake_case_ : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained(
cls.checkpoint_name , src_lang="en" , tgt_lang="fr" )
snake_case_ : List[str] = 1
return cls
def _A ( self :Tuple ) -> Union[str, Any]:
'''simple docstring'''
self.assertEqual(self.tokenizer.get_lang_id("ar" ) , 128_006 )
self.assertEqual(self.tokenizer.get_lang_id("en" ) , 128_022 )
self.assertEqual(self.tokenizer.get_lang_id("ro" ) , 128_076 )
self.assertEqual(self.tokenizer.get_lang_id("mr" ) , 128_063 )
def _A ( self :Optional[int] ) -> List[str]:
'''simple docstring'''
snake_case_ : Dict = self.tokenizer.get_vocab()
self.assertEqual(len(lowerCAmelCase__ ) , self.tokenizer.vocab_size )
self.assertEqual(vocab["<unk>"] , 3 )
self.assertIn(self.tokenizer.get_lang_token("en" ) , lowerCAmelCase__ )
def _A ( self :Any ) -> Dict:
'''simple docstring'''
snake_case_ : List[str] = "en"
snake_case_ : Dict = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , lowerCAmelCase__ )
def _A ( self :Union[str, Any] ) -> Dict:
'''simple docstring'''
self.assertIn(lowerCAmelCase__ , self.tokenizer.all_special_ids )
# fmt: off
snake_case_ : Dict = [FR_CODE, 5_364, 82, 8_642, 4, 294, 47, 8, 14_028, 136, 3_286, 9_706, 6, 90_797, 6, 144_012, 162, 88_128, 30_061, 5, 2]
# fmt: on
snake_case_ : List[str] = self.tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ )
snake_case_ : str = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCAmelCase__ )
self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ )
self.assertNotIn(self.tokenizer.eos_token , lowerCAmelCase__ )
def _A ( self :Tuple ) -> Tuple:
'''simple docstring'''
snake_case_ : Union[str, Any] = tempfile.mkdtemp()
snake_case_ : int = self.tokenizer.lang_token_to_id
self.tokenizer.save_pretrained(lowerCAmelCase__ )
snake_case_ : List[str] = MaMaaaTokenizer.from_pretrained(lowerCAmelCase__ )
self.assertDictEqual(new_tok.lang_token_to_id , lowerCAmelCase__ )
@require_torch
def _A ( self :Optional[Any] ) -> str:
'''simple docstring'''
snake_case_ : Union[str, Any] = "en"
snake_case_ : Tuple = "fr"
snake_case_ : Optional[int] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase__ , return_tensors="pt" )
snake_case_ : Dict = shift_tokens_right(
batch["labels"] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id )
for k in batch:
snake_case_ : str = batch[k].tolist()
# batch = {k: v.tolist() for k,v in batch.items()}
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
# batch.decoder_inputs_ids[0][0] ==
assert batch.input_ids[1][0] == EN_CODE
assert batch.input_ids[1][-1] == 2
assert batch.labels[1][0] == FR_CODE
assert batch.labels[1][-1] == 2
assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]
@require_torch
def _A ( self :Optional[Any] ) -> Tuple:
'''simple docstring'''
snake_case_ : List[str] = "mr"
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
snake_case_ : int = "zh"
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
@require_torch
def _A ( self :str ) -> int:
'''simple docstring'''
snake_case_ : Dict = "mr"
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
snake_case_ : Tuple = "zh"
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
@require_torch
def _A ( self :Optional[Any] ) -> Optional[int]:
'''simple docstring'''
snake_case_ : Optional[int] = self.tokenizer._build_translation_inputs("A test" , return_tensors="pt" , src_lang="en" , tgt_lang="ar" )
self.assertEqual(
nested_simplify(lowerCAmelCase__ ) , {
# en_XX, A, test, EOS
"input_ids": [[128_022, 58, 4_183, 2]],
"attention_mask": [[1, 1, 1, 1]],
# ar_AR
"forced_bos_token_id": 128_006,
} , )
| 656 | 1 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image
from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
lowerCamelCase = logging.get_logger(__name__)
def SCREAMING_SNAKE_CASE( __UpperCamelCase ) -> Union[str, Any]:
a__ : List[Any] = DPTConfig()
if "large" in checkpoint_url:
a__ : Any = 10_24
a__ : Tuple = 40_96
a__ : Dict = 24
a__ : Union[str, Any] = 16
a__ : Any = [5, 11, 17, 23]
a__ : Optional[Any] = [2_56, 5_12, 10_24, 10_24]
a__ : Tuple = (1, 3_84, 3_84)
if "ade" in checkpoint_url:
a__ : Optional[Any] = True
a__ : Dict = 1_50
a__ : Tuple = "huggingface/label-files"
a__ : Union[str, Any] = "ade20k-id2label.json"
a__ : Any = json.load(open(cached_download(hf_hub_url(__UpperCamelCase , __UpperCamelCase , repo_type="dataset" ) ) , "r" ) )
a__ : str = {int(__UpperCamelCase ): v for k, v in idalabel.items()}
a__ : Any = idalabel
a__ : Optional[Any] = {v: k for k, v in idalabel.items()}
a__ : Union[str, Any] = [1, 1_50, 4_80, 4_80]
return config, expected_shape
def SCREAMING_SNAKE_CASE( __UpperCamelCase ) -> Tuple:
a__ : Any = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
for k in ignore_keys:
state_dict.pop(__UpperCamelCase , __UpperCamelCase )
def SCREAMING_SNAKE_CASE( __UpperCamelCase ) -> str:
if (
"pretrained.model" in name
and "cls_token" not in name
and "pos_embed" not in name
and "patch_embed" not in name
):
a__ : List[Any] = name.replace("pretrained.model" , "dpt.encoder" )
if "pretrained.model" in name:
a__ : Dict = name.replace("pretrained.model" , "dpt.embeddings" )
if "patch_embed" in name:
a__ : List[Any] = name.replace("patch_embed" , "patch_embeddings" )
if "pos_embed" in name:
a__ : Optional[Any] = name.replace("pos_embed" , "position_embeddings" )
if "attn.proj" in name:
a__ : Dict = name.replace("attn.proj" , "attention.output.dense" )
if "proj" in name and "project" not in name:
a__ : List[Any] = name.replace("proj" , "projection" )
if "blocks" in name:
a__ : List[str] = name.replace("blocks" , "layer" )
if "mlp.fc1" in name:
a__ : Any = name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
a__ : List[Any] = name.replace("mlp.fc2" , "output.dense" )
if "norm1" in name:
a__ : Tuple = name.replace("norm1" , "layernorm_before" )
if "norm2" in name:
a__ : Tuple = name.replace("norm2" , "layernorm_after" )
if "scratch.output_conv" in name:
a__ : Optional[Any] = name.replace("scratch.output_conv" , "head" )
if "scratch" in name:
a__ : List[Any] = name.replace("scratch" , "neck" )
if "layer1_rn" in name:
a__ : str = name.replace("layer1_rn" , "convs.0" )
if "layer2_rn" in name:
a__ : Optional[int] = name.replace("layer2_rn" , "convs.1" )
if "layer3_rn" in name:
a__ : Optional[Any] = name.replace("layer3_rn" , "convs.2" )
if "layer4_rn" in name:
a__ : int = name.replace("layer4_rn" , "convs.3" )
if "refinenet" in name:
a__ : List[str] = int(name[len("neck.refinenet" ) : len("neck.refinenet" ) + 1] )
# tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
a__ : Tuple = name.replace(F'refinenet{layer_idx}' , F'fusion_stage.layers.{abs(layer_idx-4 )}' )
if "out_conv" in name:
a__ : str = name.replace("out_conv" , "projection" )
if "resConfUnit1" in name:
a__ : Optional[Any] = name.replace("resConfUnit1" , "residual_layer1" )
if "resConfUnit2" in name:
a__ : Optional[int] = name.replace("resConfUnit2" , "residual_layer2" )
if "conv1" in name:
a__ : List[Any] = name.replace("conv1" , "convolution1" )
if "conv2" in name:
a__ : Optional[int] = name.replace("conv2" , "convolution2" )
# readout blocks
if "pretrained.act_postprocess1.0.project.0" in name:
a__ : int = name.replace("pretrained.act_postprocess1.0.project.0" , "neck.reassemble_stage.readout_projects.0.0" )
if "pretrained.act_postprocess2.0.project.0" in name:
a__ : List[Any] = name.replace("pretrained.act_postprocess2.0.project.0" , "neck.reassemble_stage.readout_projects.1.0" )
if "pretrained.act_postprocess3.0.project.0" in name:
a__ : Dict = name.replace("pretrained.act_postprocess3.0.project.0" , "neck.reassemble_stage.readout_projects.2.0" )
if "pretrained.act_postprocess4.0.project.0" in name:
a__ : Union[str, Any] = name.replace("pretrained.act_postprocess4.0.project.0" , "neck.reassemble_stage.readout_projects.3.0" )
# resize blocks
if "pretrained.act_postprocess1.3" in name:
a__ : Dict = name.replace("pretrained.act_postprocess1.3" , "neck.reassemble_stage.layers.0.projection" )
if "pretrained.act_postprocess1.4" in name:
a__ : List[str] = name.replace("pretrained.act_postprocess1.4" , "neck.reassemble_stage.layers.0.resize" )
if "pretrained.act_postprocess2.3" in name:
a__ : Optional[Any] = name.replace("pretrained.act_postprocess2.3" , "neck.reassemble_stage.layers.1.projection" )
if "pretrained.act_postprocess2.4" in name:
a__ : str = name.replace("pretrained.act_postprocess2.4" , "neck.reassemble_stage.layers.1.resize" )
if "pretrained.act_postprocess3.3" in name:
a__ : Tuple = name.replace("pretrained.act_postprocess3.3" , "neck.reassemble_stage.layers.2.projection" )
if "pretrained.act_postprocess4.3" in name:
a__ : Any = name.replace("pretrained.act_postprocess4.3" , "neck.reassemble_stage.layers.3.projection" )
if "pretrained.act_postprocess4.4" in name:
a__ : Any = name.replace("pretrained.act_postprocess4.4" , "neck.reassemble_stage.layers.3.resize" )
if "pretrained" in name:
a__ : List[Any] = name.replace("pretrained" , "dpt" )
if "bn" in name:
a__ : List[str] = name.replace("bn" , "batch_norm" )
if "head" in name:
a__ : Tuple = name.replace("head" , "head.head" )
if "encoder.norm" in name:
a__ : int = name.replace("encoder.norm" , "layernorm" )
if "auxlayer" in name:
a__ : Tuple = name.replace("auxlayer" , "auxiliary_head.head" )
return name
def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase ) -> Union[str, Any]:
for i in range(config.num_hidden_layers ):
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
a__ : Optional[Any] = state_dict.pop(F'dpt.encoder.layer.{i}.attn.qkv.weight' )
a__ : str = state_dict.pop(F'dpt.encoder.layer.{i}.attn.qkv.bias' )
# next, add query, keys and values (in that order) to the state dict
a__ : Union[str, Any] = in_proj_weight[: config.hidden_size, :]
a__ : Tuple = in_proj_bias[: config.hidden_size]
a__ : str = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
a__ : Optional[Any] = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
a__ : Any = in_proj_weight[
-config.hidden_size :, :
]
a__ : str = in_proj_bias[-config.hidden_size :]
def SCREAMING_SNAKE_CASE( ) -> List[Any]:
a__ : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg"
a__ : List[str] = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw )
return im
@torch.no_grad()
def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Tuple:
a__ , a__ : List[str] = get_dpt_config(__UpperCamelCase )
# load original state_dict from URL
a__ : Tuple = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location="cpu" )
# remove certain keys
remove_ignore_keys_(__UpperCamelCase )
# rename keys
for key in state_dict.copy().keys():
a__ : Union[str, Any] = state_dict.pop(__UpperCamelCase )
a__ : List[Any] = val
# read in qkv matrices
read_in_q_k_v(__UpperCamelCase , __UpperCamelCase )
# load HuggingFace model
a__ : Optional[int] = DPTForSemanticSegmentation(__UpperCamelCase ) if "ade" in checkpoint_url else DPTForDepthEstimation(__UpperCamelCase )
model.load_state_dict(__UpperCamelCase )
model.eval()
# Check outputs on an image
a__ : Optional[Any] = 4_80 if "ade" in checkpoint_url else 3_84
a__ : Any = DPTImageProcessor(size=__UpperCamelCase )
a__ : List[str] = prepare_img()
a__ : Any = image_processor(__UpperCamelCase , return_tensors="pt" )
# forward pass
a__ : List[Any] = model(**__UpperCamelCase ).logits if "ade" in checkpoint_url else model(**__UpperCamelCase ).predicted_depth
# Assert logits
a__ : List[str] = torch.tensor([[6.3_1_9_9, 6.3_6_2_9, 6.4_1_4_8], [6.3_8_5_0, 6.3_6_1_5, 6.4_1_6_6], [6.3_5_1_9, 6.3_1_7_6, 6.3_5_7_5]] )
if "ade" in checkpoint_url:
a__ : Optional[int] = torch.tensor([[4.0_4_8_0, 4.2_4_2_0, 4.4_3_6_0], [4.3_1_2_4, 4.5_6_9_3, 4.8_2_6_1], [4.5_7_6_8, 4.8_9_6_5, 5.2_1_6_3]] )
assert outputs.shape == torch.Size(__UpperCamelCase )
assert (
torch.allclose(outputs[0, 0, :3, :3] , __UpperCamelCase , atol=1e-4 )
if "ade" in checkpoint_url
else torch.allclose(outputs[0, :3, :3] , __UpperCamelCase )
)
Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase )
print(F'Saving model to {pytorch_dump_folder_path}' )
model.save_pretrained(__UpperCamelCase )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(__UpperCamelCase )
if push_to_hub:
print("Pushing model to hub..." )
model.push_to_hub(
repo_path_or_name=Path(__UpperCamelCase , __UpperCamelCase ) , organization="nielsr" , commit_message="Add model" , use_temp_dir=__UpperCamelCase , )
image_processor.push_to_hub(
repo_path_or_name=Path(__UpperCamelCase , __UpperCamelCase ) , organization="nielsr" , commit_message="Add image processor" , use_temp_dir=__UpperCamelCase , )
if __name__ == "__main__":
lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--checkpoint_url""",
default="""https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt""",
type=str,
help="""URL of the original DPT checkpoint you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the output PyTorch model directory.""",
)
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
)
parser.add_argument(
"""--model_name""",
default="""dpt-large""",
type=str,
help="""Name of the model, in case you're pushing to the hub.""",
)
lowerCamelCase = parser.parse_args()
convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
| 191 |
import argparse
import json
import os
import tensorstore as ts
import torch
from flax import serialization
from flax.traverse_util import flatten_dict, unflatten_dict
from tensorflow.io import gfile
from transformers.modeling_utils import dtype_byte_size
from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import (
rename_keys,
)
from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
from transformers.utils.hub import convert_file_size_to_int
def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase ) -> Optional[Any]:
if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3:
# expert layer
a__ : List[str] = flax_key_tuple[:-1] + ("weight",)
a__ : Optional[int] = torch.permute(__UpperCamelCase , (0, 2, 1) )
elif flax_key_tuple[-1] == "kernel" and ".".join(__UpperCamelCase ):
# linear layer
a__ : Tuple = flax_key_tuple[:-1] + ("weight",)
a__ : Tuple = flax_tensor.T
elif flax_key_tuple[-1] in ["scale", "embedding"]:
a__ : str = flax_key_tuple[:-1] + ("weight",)
return flax_key_tuple, flax_tensor
def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> List[Any]:
if "metadata" in layer:
a__ : Union[str, Any] = layer.split("metadata" )
a__ : Any = "".join(split_layer[0] )[:-1]
a__ : Optional[int] = [tuple(("metadata" + split_layer[1]).split("/" ) )]
elif "kvstore" in layer:
a__ : Optional[int] = layer.split("kvstore" )
a__ : Union[str, Any] = "".join(split_layer[0] )[:-1]
a__ : Optional[Any] = [tuple(("kvstore" + split_layer[1]).split("/" ) )]
else:
a__ : Any = layer.split("/" )
a__ : Union[str, Any] = "/".join(split_layer[:-1] )
a__ : Tuple = (split_layer[-1],)
if "kvstore/path" in layer:
a__ : Tuple = F'{switch_checkpoint_path}/{checkpoint_info[layer]}'
elif "kvstore/driver" in layer:
a__ : int = "file"
else:
a__ : List[str] = checkpoint_info[layer]
return curr_real_layer_name, split_layer, content
def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase ) -> Optional[int]:
a__ : List[Any] = rename_keys(__UpperCamelCase )
a__ : Tuple = {}
for k, v in current_block.items():
a__ : str = v
a__ : Optional[int] = new_current_block
torch.save(__UpperCamelCase , __UpperCamelCase )
def SCREAMING_SNAKE_CASE( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = WEIGHTS_NAME ) -> Any:
a__ : Optional[Any] = convert_file_size_to_int(__UpperCamelCase )
a__ : Tuple = []
a__ : Dict = {}
a__ : str = 0
a__ : Tuple = 0
os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase )
with gfile.GFile(switch_checkpoint_path + "/checkpoint" , "rb" ) as fp:
a__ : Any = serialization.msgpack_restore(fp.read() )["optimizer"]["target"]
a__ : Tuple = flatten_dict(__UpperCamelCase , sep="/" )
a__ : Any = {}
for layer in checkpoint_info.keys():
a__ , a__ , a__ : Optional[Any] = get_key_and_tensorstore_dict(
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
if curr_real_layer_name in all_layers:
a__ : int = content
else:
a__ : List[Any] = {split_layer[-1]: content}
for key in all_layers.keys():
# open tensorstore file
a__ : Tuple = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result()
a__ : Tuple = torch.tensor(__UpperCamelCase )
a__ : str = raw_weights.numel() * dtype_byte_size(raw_weights.dtype )
# use the renaming pattern from the small conversion scripts
a__ , a__ : int = rename_base_flax_keys(tuple(key.split("/" ) ) , __UpperCamelCase )
a__ : Union[str, Any] = "/".join(__UpperCamelCase )
# If this weight is going to tip up over the maximal size, we split.
if current_block_size + weight_size > max_shard_size:
a__ : int = os.path.join(
__UpperCamelCase , weights_name.replace(".bin" , F'-{len(__UpperCamelCase )+1:05d}-of-???.bin' ) )
rename_and_save_block(__UpperCamelCase , __UpperCamelCase )
sharded_state_dicts.append(current_block.keys() )
del current_block
a__ : int = {}
a__ : Optional[int] = 0
a__ : List[str] = raw_weights.to(getattr(__UpperCamelCase , __UpperCamelCase ) )
current_block_size += weight_size
total_size += weight_size
# Add the last block
a__ : Optional[int] = os.path.join(__UpperCamelCase , weights_name.replace(".bin" , F'-{len(__UpperCamelCase )+1:05d}-of-???.bin' ) )
rename_and_save_block(__UpperCamelCase , __UpperCamelCase )
sharded_state_dicts.append(current_block.keys() )
# If we only have one shard, we return it
if len(__UpperCamelCase ) == 1:
return {weights_name: sharded_state_dicts[0]}, None
# Otherwise, let's build the index
a__ : int = {}
a__ : Tuple = {}
for idx, shard in enumerate(__UpperCamelCase ):
a__ : Tuple = weights_name.replace(
".bin" , F'-{idx+1:05d}-of-{len(__UpperCamelCase ):05d}.bin' ) # len(sharded_state_dicts):05d}
a__ : Optional[int] = os.path.join(__UpperCamelCase , weights_name.replace(".bin" , F'-{idx+1:05d}-of-???.bin' ) )
os.rename(__UpperCamelCase , os.path.join(__UpperCamelCase , __UpperCamelCase ) )
a__ : List[str] = shard
for key in shard:
a__ : Tuple = shard_file
# Add the metadata
a__ : int = {"total_size": total_size}
a__ : List[str] = {"metadata": metadata, "weight_map": weight_map}
with open(os.path.join(__UpperCamelCase , __UpperCamelCase ) , "w" , encoding="utf-8" ) as f:
a__ : List[str] = json.dumps(__UpperCamelCase , indent=2 , sort_keys=__UpperCamelCase ) + "\n"
f.write(__UpperCamelCase )
return metadata, index
if __name__ == "__main__":
lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--switch_t5x_checkpoint_path""",
default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""",
type=str,
required=False,
help="""Path to a directory containing a folder per layer. Follows the original Google format.""",
)
parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""")
parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""")
parser.add_argument(
"""--pytorch_dump_folder_path""",
default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""",
type=str,
required=False,
help="""Path to the output pytorch model.""",
)
lowerCamelCase = parser.parse_args()
shard_on_the_fly(
args.switch_tax_checkpoint_path,
args.pytorch_dump_folder_path,
args.max_shard_size,
args.dtype,
)
def SCREAMING_SNAKE_CASE( ) -> int:
from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer
a__ : Any = SwitchTransformersConfig.from_pretrained("google/switch-base-8" )
config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" )
a__ : List[str] = SwitchTransformersForConditionalGeneration.from_pretrained(
"/home/arthur_huggingface_co/transformers/switch_converted" , device_map="auto" )
a__ : str = TaTokenizer.from_pretrained("t5-small" )
a__ : Tuple = "A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>."
a__ : Optional[int] = tokenizer(__UpperCamelCase , return_tensors="pt" ).input_ids
a__ : Optional[Any] = model.generate(__UpperCamelCase , decoder_start_token_id=0 )
print(tokenizer.decode(out[0] ) )
| 191 | 1 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: List[str] = ["flax"]
def __init__( self : int , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Any ) -> int:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Any , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : List[Any] ) -> int:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Dict , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Optional[int] = ["flax"]
def __init__( self : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : List[Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Tuple ) -> int:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : int , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) -> Dict:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: List[str] = ["flax"]
def __init__( self : Any , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : str , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ) -> List[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : List[Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : int ) -> Tuple:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Union[str, Any] = ["flax"]
def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Tuple , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : str ) -> Any:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Tuple , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any] ) -> List[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: List[str] = ["flax"]
def __init__( self : Any , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[Any] ) -> List[Any]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : int , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Any ) -> Dict:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Any ) -> Optional[int]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: List[str] = ["flax"]
def __init__( self : List[Any] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[str] ) -> Union[str, Any]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Any , *UpperCAmelCase_ : int , **UpperCAmelCase_ : List[str] ) -> Any:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Dict , *UpperCAmelCase_ : int , **UpperCAmelCase_ : str ) -> Any:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: List[str] = ["flax"]
def __init__( self : Union[str, Any] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any] ) -> Dict:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : List[Any] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : int ) -> Tuple:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : int , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Any = ["flax"]
def __init__( self : List[str] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Any ) -> Optional[Any]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Dict , *UpperCAmelCase_ : int , **UpperCAmelCase_ : List[Any] ) -> List[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : List[Any] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Tuple ) -> Dict:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: str = ["flax"]
def __init__( self : Tuple , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any] ) -> Any:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Tuple , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : str ) -> List[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Union[str, Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Any ) -> Optional[int]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Tuple = ["flax"]
def __init__( self : Tuple , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Tuple ) -> str:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Any ) -> List[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Optional[int] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Tuple ) -> List[str]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: str = ["flax"]
def __init__( self : int , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : List[Any] ) -> List[str]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Optional[int] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : List[Any] ) -> Optional[Any]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Optional[Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Tuple ) -> Optional[int]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Optional[int] = ["flax"]
def __init__( self : Dict , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Union[str, Any] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Optional[int] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Union[str, Any] ) -> Any:
"""simple docstring"""
requires_backends(cls , ['flax'] )
class _SCREAMING_SNAKE_CASE ( metaclass=UpperCAmelCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Optional[int] = ["flax"]
def __init__( self : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Tuple ) -> Any:
"""simple docstring"""
requires_backends(self , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : int , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any ) -> Dict:
"""simple docstring"""
requires_backends(cls , ['flax'] )
@classmethod
def __lowerCamelCase ( cls : Any , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ) -> int:
"""simple docstring"""
requires_backends(cls , ['flax'] )
| 720 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __lowerCamelCase ( self : Any ) -> Dict:
"""simple docstring"""
_lowerCAmelCase = 10
def __lowerCamelCase ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
_lowerCAmelCase = [1, 2, 3, 4]
_lowerCAmelCase = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
self.assertEqual(truncate_or_pad(UpperCAmelCase_ , self.block_size , 0 ) , UpperCAmelCase_ )
def __lowerCamelCase ( self : Optional[int] ) -> int:
"""simple docstring"""
_lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(UpperCAmelCase_ , self.block_size , 0 ) , UpperCAmelCase_ )
def __lowerCamelCase ( self : List[Any] ) -> int:
"""simple docstring"""
_lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
_lowerCAmelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(UpperCAmelCase_ , self.block_size , 0 ) , UpperCAmelCase_ )
def __lowerCamelCase ( self : str ) -> Optional[int]:
"""simple docstring"""
_lowerCAmelCase = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.'
_lowerCAmelCase , _lowerCAmelCase = process_story(UpperCAmelCase_ )
self.assertEqual(UpperCAmelCase_ , [] )
def __lowerCamelCase ( self : Dict ) -> Union[str, Any]:
"""simple docstring"""
_lowerCAmelCase = ''
_lowerCAmelCase , _lowerCAmelCase = process_story(UpperCAmelCase_ )
self.assertEqual(UpperCAmelCase_ , [] )
self.assertEqual(UpperCAmelCase_ , [] )
def __lowerCamelCase ( self : Optional[int] ) -> List[str]:
"""simple docstring"""
_lowerCAmelCase = (
'It was the year of Our Lord one thousand seven hundred and '
'seventy-five\n\nSpiritual revelations were conceded to England '
'at that favoured period, as at this.\n@highlight\n\nIt was the best of times'
)
_lowerCAmelCase , _lowerCAmelCase = process_story(UpperCAmelCase_ )
_lowerCAmelCase = [
'It was the year of Our Lord one thousand seven hundred and seventy-five.',
'Spiritual revelations were conceded to England at that favoured period, as at this.',
]
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ )
_lowerCAmelCase = ['It was the best of times.']
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ )
def __lowerCamelCase ( self : List[str] ) -> int:
"""simple docstring"""
_lowerCAmelCase = torch.tensor([1, 2, 3, 4] )
_lowerCAmelCase = torch.tensor([1, 1, 1, 1] )
np.testing.assert_array_equal(build_mask(UpperCAmelCase_ , 0 ).numpy() , expected.numpy() )
def __lowerCamelCase ( self : int ) -> str:
"""simple docstring"""
_lowerCAmelCase = torch.tensor([1, 2, 3, 4, 23, 23, 23] )
_lowerCAmelCase = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(UpperCAmelCase_ , 23 ).numpy() , expected.numpy() )
def __lowerCamelCase ( self : int ) -> Union[str, Any]:
"""simple docstring"""
_lowerCAmelCase = torch.tensor([8, 2, 3, 4, 1, 1, 1] )
_lowerCAmelCase = torch.tensor([1, 1, 1, 1, 0, 0, 0] )
np.testing.assert_array_equal(build_mask(UpperCAmelCase_ , 1 ).numpy() , expected.numpy() )
def __lowerCamelCase ( self : str ) -> int:
"""simple docstring"""
_lowerCAmelCase = 101
_lowerCAmelCase = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] )
_lowerCAmelCase = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] )
_lowerCAmelCase = compute_token_type_ids(UpperCAmelCase_ , UpperCAmelCase_ )
np.testing.assert_array_equal(UpperCAmelCase_ , UpperCAmelCase_ )
| 491 | 0 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
UpperCAmelCase__ :Optional[Any] = logging.get_logger(__name__)
UpperCAmelCase__ :Any = {
"salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : Union[str, Any] = 'blip_2_vision_model'
def __init__( self : Tuple , A__ : Union[str, Any]=1408 , A__ : Dict=6144 , A__ : Optional[int]=39 , A__ : List[Any]=16 , A__ : str=224 , A__ : Tuple=14 , A__ : Any="gelu" , A__ : str=0.0_0001 , A__ : List[Any]=0.0 , A__ : str=1e-1_0 , A__ : Any=True , **A__ : List[Any] , ):
"""simple docstring"""
super().__init__(**_a )
__lowerCamelCase : Any = hidden_size
__lowerCamelCase : int = intermediate_size
__lowerCamelCase : int = num_hidden_layers
__lowerCamelCase : int = num_attention_heads
__lowerCamelCase : Tuple = patch_size
__lowerCamelCase : Optional[int] = image_size
__lowerCamelCase : List[str] = initializer_range
__lowerCamelCase : Optional[Any] = attention_dropout
__lowerCamelCase : Tuple = layer_norm_eps
__lowerCamelCase : List[Any] = hidden_act
__lowerCamelCase : Tuple = qkv_bias
@classmethod
def a_ ( cls : Tuple , A__ : Tuple , **A__ : Optional[Any] ):
"""simple docstring"""
cls._set_token_in_kwargs(_a )
__lowerCamelCase : List[str] = cls.get_config_dict(_a , **_a )
# get the vision config dict if we are loading from Blip2Config
if config_dict.get("""model_type""" ) == "blip-2":
__lowerCamelCase : Optional[Any] = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." )
return cls.from_dict(_a , **_a )
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : Dict = 'blip_2_qformer'
def __init__( self : str , A__ : Any=30522 , A__ : int=768 , A__ : str=12 , A__ : Union[str, Any]=12 , A__ : int=3072 , A__ : str="gelu" , A__ : Union[str, Any]=0.1 , A__ : Union[str, Any]=0.1 , A__ : Optional[int]=512 , A__ : Union[str, Any]=0.02 , A__ : Optional[int]=1e-1_2 , A__ : List[Any]=0 , A__ : str="absolute" , A__ : Tuple=2 , A__ : Optional[int]=1408 , **A__ : List[str] , ):
"""simple docstring"""
super().__init__(pad_token_id=_a , **_a )
__lowerCamelCase : str = vocab_size
__lowerCamelCase : int = hidden_size
__lowerCamelCase : Union[str, Any] = num_hidden_layers
__lowerCamelCase : Tuple = num_attention_heads
__lowerCamelCase : Optional[Any] = hidden_act
__lowerCamelCase : List[Any] = intermediate_size
__lowerCamelCase : Optional[int] = hidden_dropout_prob
__lowerCamelCase : Tuple = attention_probs_dropout_prob
__lowerCamelCase : str = max_position_embeddings
__lowerCamelCase : int = initializer_range
__lowerCamelCase : str = layer_norm_eps
__lowerCamelCase : Union[str, Any] = position_embedding_type
__lowerCamelCase : Any = cross_attention_frequency
__lowerCamelCase : Optional[Any] = encoder_hidden_size
@classmethod
def a_ ( cls : Any , A__ : List[str] , **A__ : Tuple ):
"""simple docstring"""
cls._set_token_in_kwargs(_a )
__lowerCamelCase : Optional[Any] = cls.get_config_dict(_a , **_a )
# get the qformer config dict if we are loading from Blip2Config
if config_dict.get("""model_type""" ) == "blip-2":
__lowerCamelCase : str = config_dict["qformer_config"]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." )
return cls.from_dict(_a , **_a )
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : str = 'blip-2'
snake_case__ : List[Any] = True
def __init__( self : List[str] , A__ : Union[str, Any]=None , A__ : Dict=None , A__ : List[Any]=None , A__ : Optional[int]=32 , **A__ : Optional[Any] ):
"""simple docstring"""
super().__init__(**_a )
if vision_config is None:
__lowerCamelCase : int = {}
logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" )
if qformer_config is None:
__lowerCamelCase : List[Any] = {}
logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" )
if text_config is None:
__lowerCamelCase : List[str] = {}
logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" )
__lowerCamelCase : Optional[int] = BlipaVisionConfig(**_a )
__lowerCamelCase : Dict = BlipaQFormerConfig(**_a )
__lowerCamelCase : Optional[int] = text_config["model_type"] if "model_type" in text_config else "opt"
__lowerCamelCase : Tuple = CONFIG_MAPPING[text_model_type](**_a )
__lowerCamelCase : List[Any] = self.text_config.tie_word_embeddings
__lowerCamelCase : int = self.text_config.is_encoder_decoder
__lowerCamelCase : Tuple = num_query_tokens
__lowerCamelCase : Union[str, Any] = self.vision_config.hidden_size
__lowerCamelCase : List[str] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
__lowerCamelCase : Tuple = 1.0
__lowerCamelCase : Tuple = 0.02
@classmethod
def a_ ( cls : Union[str, Any] , A__ : List[Any] , A__ : int , A__ : str , **A__ : Optional[int] , ):
"""simple docstring"""
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_a , )
def a_ ( self : str ):
"""simple docstring"""
__lowerCamelCase : Union[str, Any] = copy.deepcopy(self.__dict__ )
__lowerCamelCase : List[str] = self.vision_config.to_dict()
__lowerCamelCase : Tuple = self.qformer_config.to_dict()
__lowerCamelCase : Union[str, Any] = self.text_config.to_dict()
__lowerCamelCase : Optional[int] = self.__class__.model_type
return output
| 150 |
from typing import List, Optional, Union
import torch
from transformers import (
XLMRobertaTokenizer,
)
from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
is_accelerate_available,
is_accelerate_version,
logging,
randn_tensor,
replace_example_docstring,
)
from .text_encoder import MultilingualCLIP
snake_case : str = logging.get_logger(__name__) # pylint: disable=invalid-name
snake_case : Optional[int] = "\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\")\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"red cat, 4k photo\"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\")\n >>> pipe.to(\"cuda\")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save(\"cat.png\")\n ```\n"
def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Any , _snake_case : Optional[Any]=8 ) -> Tuple:
'''simple docstring'''
__magic_name__ : List[str] = h // scale_factor**2
if h % scale_factor**2 != 0:
new_h += 1
__magic_name__ : Dict = w // scale_factor**2
if w % scale_factor**2 != 0:
new_w += 1
return new_h * scale_factor, new_w * scale_factor
class _snake_case ( snake_case ):
def __init__( self , _a , _a , _a , _a , _a , ):
super().__init__()
self.register_modules(
text_encoder=_a , tokenizer=_a , unet=_a , scheduler=_a , movq=_a , )
__magic_name__ : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a ):
if latents is None:
__magic_name__ : List[Any] = 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}''' )
__magic_name__ : Optional[Any] = latents.to(_a )
__magic_name__ : Optional[Any] = latents * scheduler.init_noise_sigma
return latents
def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a=None , ):
__magic_name__ : List[str] = len(_a ) if isinstance(_a , _a ) else 1
# get prompt text embeddings
__magic_name__ : str = self.tokenizer(
_a , padding="max_length" , truncation=_a , max_length=77 , return_attention_mask=_a , add_special_tokens=_a , return_tensors="pt" , )
__magic_name__ : Optional[Any] = text_inputs.input_ids
__magic_name__ : Union[str, Any] = self.tokenizer(_a , padding="longest" , return_tensors="pt" ).input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_a , _a ):
__magic_name__ : Any = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] )
logger.warning(
"The following part of your input was truncated because CLIP can only handle sequences up to"
f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' )
__magic_name__ : Union[str, Any] = text_input_ids.to(_a )
__magic_name__ : str = text_inputs.attention_mask.to(_a )
__magic_name__ , __magic_name__ : Any = self.text_encoder(
input_ids=_a , attention_mask=_a )
__magic_name__ : List[Any] = prompt_embeds.repeat_interleave(_a , dim=0 )
__magic_name__ : Any = text_encoder_hidden_states.repeat_interleave(_a , dim=0 )
__magic_name__ : Optional[int] = text_mask.repeat_interleave(_a , dim=0 )
if do_classifier_free_guidance:
__magic_name__ : List[str]
if negative_prompt is None:
__magic_name__ : Optional[int] = [""] * batch_size
elif type(_a ) is not type(_a ):
raise TypeError(
f'''`negative_prompt` should be the same type to `prompt`, but got {type(_a )} !='''
f''' {type(_a )}.''' )
elif isinstance(_a , _a ):
__magic_name__ : Tuple = [negative_prompt]
elif batch_size != len(_a ):
raise ValueError(
f'''`negative_prompt`: {negative_prompt} has batch size {len(_a )}, but `prompt`:'''
f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
" the batch size of `prompt`." )
else:
__magic_name__ : Union[str, Any] = negative_prompt
__magic_name__ : List[Any] = self.tokenizer(
_a , padding="max_length" , max_length=77 , truncation=_a , return_attention_mask=_a , add_special_tokens=_a , return_tensors="pt" , )
__magic_name__ : str = uncond_input.input_ids.to(_a )
__magic_name__ : Any = uncond_input.attention_mask.to(_a )
__magic_name__ , __magic_name__ : str = self.text_encoder(
input_ids=_a , attention_mask=_a )
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
__magic_name__ : Tuple = negative_prompt_embeds.shape[1]
__magic_name__ : Union[str, Any] = negative_prompt_embeds.repeat(1 , _a )
__magic_name__ : str = negative_prompt_embeds.view(batch_size * num_images_per_prompt , _a )
__magic_name__ : Tuple = uncond_text_encoder_hidden_states.shape[1]
__magic_name__ : str = uncond_text_encoder_hidden_states.repeat(1 , _a , 1 )
__magic_name__ : int = uncond_text_encoder_hidden_states.view(
batch_size * num_images_per_prompt , _a , -1 )
__magic_name__ : Optional[int] = uncond_text_mask.repeat_interleave(_a , dim=0 )
# done duplicates
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
__magic_name__ : List[Any] = torch.cat([negative_prompt_embeds, prompt_embeds] )
__magic_name__ : Tuple = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] )
__magic_name__ : Optional[int] = torch.cat([uncond_text_mask, text_mask] )
return prompt_embeds, text_encoder_hidden_states, text_mask
def SCREAMING_SNAKE_CASE ( self , _a=0 ):
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError("Please install accelerate via `pip install accelerate`" )
__magic_name__ : Tuple = torch.device(f'''cuda:{gpu_id}''' )
__magic_name__ : Union[str, Any] = [
self.unet,
self.text_encoder,
self.movq,
]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(_a , _a )
def SCREAMING_SNAKE_CASE ( self , _a=0 ):
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." )
__magic_name__ : int = 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)
__magic_name__ : List[str] = None
for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
__magic_name__ , __magic_name__ : Any = cpu_offload_with_hook(_a , _a , prev_module_hook=_a )
if self.safety_checker is not None:
__magic_name__ , __magic_name__ : Optional[int] = cpu_offload_with_hook(self.safety_checker , _a , prev_module_hook=_a )
# We'll offload the last model manually.
__magic_name__ : List[Any] = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def SCREAMING_SNAKE_CASE ( self ):
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 , _a , _a , _a , _a = None , _a = 512 , _a = 512 , _a = 100 , _a = 4.0 , _a = 1 , _a = None , _a = None , _a = "pil" , _a = True , ):
if isinstance(_a , _a ):
__magic_name__ : Dict = 1
elif isinstance(_a , _a ):
__magic_name__ : Union[str, Any] = len(_a )
else:
raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(_a )}''' )
__magic_name__ : Dict = self._execution_device
__magic_name__ : List[str] = batch_size * num_images_per_prompt
__magic_name__ : Tuple = guidance_scale > 1.0
__magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = self._encode_prompt(
_a , _a , _a , _a , _a )
if isinstance(_a , _a ):
__magic_name__ : Any = torch.cat(_a , dim=0 )
if isinstance(_a , _a ):
__magic_name__ : str = torch.cat(_a , dim=0 )
if do_classifier_free_guidance:
__magic_name__ : str = image_embeds.repeat_interleave(_a , dim=0 )
__magic_name__ : Tuple = negative_image_embeds.repeat_interleave(_a , dim=0 )
__magic_name__ : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(
dtype=prompt_embeds.dtype , device=_a )
self.scheduler.set_timesteps(_a , device=_a )
__magic_name__ : str = self.scheduler.timesteps
__magic_name__ : Union[str, Any] = self.unet.config.in_channels
__magic_name__ , __magic_name__ : str = get_new_h_w(_a , _a , self.movq_scale_factor )
# create initial latent
__magic_name__ : Optional[Any] = self.prepare_latents(
(batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.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
__magic_name__ : int = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
__magic_name__ : Any = {"text_embeds": prompt_embeds, "image_embeds": image_embeds}
__magic_name__ : Optional[Any] = self.unet(
sample=_a , timestep=_a , encoder_hidden_states=_a , added_cond_kwargs=_a , return_dict=_a , )[0]
if do_classifier_free_guidance:
__magic_name__ , __magic_name__ : Dict = noise_pred.split(latents.shape[1] , dim=1 )
__magic_name__ , __magic_name__ : Optional[int] = noise_pred.chunk(2 )
__magic_name__ , __magic_name__ : int = variance_pred.chunk(2 )
__magic_name__ : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
__magic_name__ : Any = 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"]
):
__magic_name__ , __magic_name__ : Tuple = noise_pred.split(latents.shape[1] , dim=1 )
# compute the previous noisy sample x_t -> x_t-1
__magic_name__ : str = self.scheduler.step(
_a , _a , _a , generator=_a , ).prev_sample
# post-processing
__magic_name__ : Optional[int] = 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"]:
__magic_name__ : str = image * 0.5 + 0.5
__magic_name__ : Optional[int] = image.clamp(0 , 1 )
__magic_name__ : int = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
__magic_name__ : Any = self.numpy_to_pil(_a )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=_a )
| 124 | 0 |
import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List
from ..utils import logging
UpperCAmelCase_ = logging.get_logger(__name__)
def UpperCamelCase ( lowerCAmelCase_=None , lowerCAmelCase_=None ) -> str:
'''simple docstring'''
return field(default_factory=lambda: default , metadata=lowerCAmelCase_ )
@dataclass
class lowerCAmelCase :
_SCREAMING_SNAKE_CASE : List[str] =list_field(
default=[] , metadata={
"""help""": (
"""Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
""" of all available models"""
)
} , )
_SCREAMING_SNAKE_CASE : List[int] =list_field(
default=[8] , metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""} )
_SCREAMING_SNAKE_CASE : List[int] =list_field(
default=[8, 32, 128, 512] , metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""} , )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""} , )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""} , )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""} )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Use FP16 to accelerate inference."""} )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Benchmark training of model"""} )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Verbose memory tracing"""} )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""} , )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={
"""help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
} , )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Trace memory line by line"""} )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Save result to a CSV file"""} )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Save all print statements in a log file"""} )
_SCREAMING_SNAKE_CASE : bool =field(default=_a , metadata={"""help""": """Whether to print environment information"""} )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={
"""help""": (
"""Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
""" multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
""" for debugging / testing and on TPU."""
)
} , )
_SCREAMING_SNAKE_CASE : str =field(
default=F'inference_time_{round(time() )}.csv' , metadata={"""help""": """CSV filename used if saving time results to csv."""} , )
_SCREAMING_SNAKE_CASE : str =field(
default=F'inference_memory_{round(time() )}.csv' , metadata={"""help""": """CSV filename used if saving memory results to csv."""} , )
_SCREAMING_SNAKE_CASE : str =field(
default=F'train_time_{round(time() )}.csv' , metadata={"""help""": """CSV filename used if saving time results to csv for training."""} , )
_SCREAMING_SNAKE_CASE : str =field(
default=F'train_memory_{round(time() )}.csv' , metadata={"""help""": """CSV filename used if saving memory results to csv for training."""} , )
_SCREAMING_SNAKE_CASE : str =field(
default=F'env_info_{round(time() )}.csv' , metadata={"""help""": """CSV filename used if saving environment information."""} , )
_SCREAMING_SNAKE_CASE : str =field(
default=F'log_{round(time() )}.csv' , metadata={"""help""": """Log filename used if print statements are saved in log."""} , )
_SCREAMING_SNAKE_CASE : int =field(default=3 , metadata={"""help""": """Times an experiment will be run."""} )
_SCREAMING_SNAKE_CASE : bool =field(
default=_a , metadata={
"""help""": (
"""Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
""" model weights."""
)
} , )
def a__ ( self ):
warnings.warn(
f"The class {self.__class__} is deprecated. Hugging Face Benchmarking utils"
' are deprecated in general and it is advised to use external Benchmarking libraries '
' to benchmark Transformer models.' , lowerCAmelCase__ , )
def a__ ( self ):
return json.dumps(dataclasses.asdict(self ) , indent=2 )
@property
def a__ ( self ):
if len(self.models ) <= 0:
raise ValueError(
'Please make sure you provide at least one model name / model identifier, *e.g.* `--models'
' bert-base-cased` or `args.models = [\'bert-base-cased\'].' )
return self.models
@property
def a__ ( self ):
if not self.multi_process:
return False
elif self.is_tpu:
logger.info('Multiprocessing is currently not possible on TPU.' )
return False
else:
return True | 476 | import warnings
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = {
'''nvidia/segformer-b0-finetuned-ade-512-512''': (
'''https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'''
),
# See all SegFormer models at https://huggingface.co/models?filter=segformer
}
class lowerCAmelCase ( _a ):
_SCREAMING_SNAKE_CASE : Tuple ="""segformer"""
def __init__( self , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=[2, 2, 2, 2] , lowerCAmelCase__=[8, 4, 2, 1] , lowerCAmelCase__=[32, 64, 160, 256] , lowerCAmelCase__=[7, 3, 3, 3] , lowerCAmelCase__=[4, 2, 2, 2] , lowerCAmelCase__=[1, 2, 5, 8] , lowerCAmelCase__=[4, 4, 4, 4] , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.02 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1E-6 , lowerCAmelCase__=256 , lowerCAmelCase__=255 , **lowerCAmelCase__ , ):
super().__init__(**lowerCAmelCase__ )
if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
warnings.warn(
'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
' removed, as the behaviour will default to that of reshape_last_stage = True.' , lowerCAmelCase__ , )
_A= num_channels
_A= num_encoder_blocks
_A= depths
_A= sr_ratios
_A= hidden_sizes
_A= patch_sizes
_A= strides
_A= mlp_ratios
_A= num_attention_heads
_A= hidden_act
_A= hidden_dropout_prob
_A= attention_probs_dropout_prob
_A= classifier_dropout_prob
_A= initializer_range
_A= drop_path_rate
_A= layer_norm_eps
_A= decoder_hidden_size
_A= kwargs.get('reshape_last_stage' , lowerCAmelCase__ )
_A= semantic_loss_ignore_index
class lowerCAmelCase ( _a ):
_SCREAMING_SNAKE_CASE : List[str] =version.parse("""1.11""" )
@property
def a__ ( self ):
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def a__ ( self ):
return 1E-4
@property
def a__ ( self ):
return 12 | 476 | 1 |
from __future__ import annotations
import time
lowerCamelCase =list[tuple[int, int]]
lowerCamelCase =[
[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],
]
lowerCamelCase =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class _lowerCamelCase :
"""simple docstring"""
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[Any]:
"""simple docstring"""
UpperCamelCase__ : Union[str, Any] = pos_x
UpperCamelCase__ : int = pos_y
UpperCamelCase__ : Union[str, Any] = (pos_y, pos_x)
UpperCamelCase__ : Optional[int] = goal_x
UpperCamelCase__ : Tuple = goal_y
UpperCamelCase__ : List[str] = parent
class _lowerCamelCase :
"""simple docstring"""
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Any:
"""simple docstring"""
UpperCamelCase__ : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Any = [self.start]
UpperCamelCase__ : int = False
def __SCREAMING_SNAKE_CASE ( self ) -> Path | None:
"""simple docstring"""
while self.node_queue:
UpperCamelCase__ : Union[str, Any] = self.node_queue.pop(0 )
if current_node.pos == self.target.pos:
UpperCamelCase__ : Tuple = True
return self.retrace_path(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = self.get_successors(__SCREAMING_SNAKE_CASE )
for node in successors:
self.node_queue.append(__SCREAMING_SNAKE_CASE )
if not self.reached:
return [self.start.pos]
return None
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE ) -> list[Node]:
"""simple docstring"""
UpperCamelCase__ : Optional[Any] = []
for action in delta:
UpperCamelCase__ : Optional[int] = parent.pos_x + action[1]
UpperCamelCase__ : List[Any] = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__SCREAMING_SNAKE_CASE ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , __SCREAMING_SNAKE_CASE ) )
return successors
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE ) -> Path:
"""simple docstring"""
UpperCamelCase__ : Tuple = node
UpperCamelCase__ : int = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
UpperCamelCase__ : Any = current_node.parent
path.reverse()
return path
class _lowerCamelCase :
"""simple docstring"""
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase__ : int = BreadthFirstSearch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = BreadthFirstSearch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Union[str, Any] = False
def __SCREAMING_SNAKE_CASE ( self ) -> Path | None:
"""simple docstring"""
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
UpperCamelCase__ : List[str] = self.fwd_bfs.node_queue.pop(0 )
UpperCamelCase__ : str = self.bwd_bfs.node_queue.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
UpperCamelCase__ : Optional[int] = True
return self.retrace_bidirectional_path(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = current_bwd_node
UpperCamelCase__ : Tuple = current_fwd_node
UpperCamelCase__ : int = {
self.fwd_bfs: self.fwd_bfs.get_successors(__SCREAMING_SNAKE_CASE ),
self.bwd_bfs: self.bwd_bfs.get_successors(__SCREAMING_SNAKE_CASE ),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(__SCREAMING_SNAKE_CASE )
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def __SCREAMING_SNAKE_CASE ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Path:
"""simple docstring"""
UpperCamelCase__ : Optional[Any] = self.fwd_bfs.retrace_path(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = self.bwd_bfs.retrace_path(__SCREAMING_SNAKE_CASE )
bwd_path.pop()
bwd_path.reverse()
UpperCamelCase__ : int = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
lowerCamelCase =(0, 0)
lowerCamelCase =(len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
lowerCamelCase =time.time()
lowerCamelCase =BreadthFirstSearch(init, goal)
lowerCamelCase =bfs.search()
lowerCamelCase =time.time() - start_bfs_time
print("Unidirectional BFS computation time : ", bfs_time)
lowerCamelCase =time.time()
lowerCamelCase =BidirectionalBreadthFirstSearch(init, goal)
lowerCamelCase =bd_bfs.search()
lowerCamelCase =time.time() - start_bd_bfs_time
print("Bidirectional BFS computation time : ", bd_bfs_time)
| 285 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCamelCase =logging.get_logger(__name__)
lowerCamelCase ={
"facebook/wav2vec2-base-960h": "https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json",
# See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}
class _lowerCamelCase ( UpperCamelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = '''wav2vec2'''
def __init__( self , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=3_0_7_2 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-5 , __SCREAMING_SNAKE_CASE="group" , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , __SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2) , __SCREAMING_SNAKE_CASE=(1_0, 3, 3, 3, 3, 2, 2) , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=1_2_8 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.05 , __SCREAMING_SNAKE_CASE=1_0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1_0 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=3_2_0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1_0_0 , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="sum" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , __SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1) , __SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1) , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ) -> str:
"""simple docstring"""
super().__init__(**__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = hidden_size
UpperCamelCase__ : List[Any] = feat_extract_norm
UpperCamelCase__ : Union[str, Any] = feat_extract_activation
UpperCamelCase__ : Union[str, Any] = list(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = list(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = list(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Tuple = conv_bias
UpperCamelCase__ : Optional[Any] = num_conv_pos_embeddings
UpperCamelCase__ : Tuple = num_conv_pos_embedding_groups
UpperCamelCase__ : Tuple = len(self.conv_dim )
UpperCamelCase__ : Optional[Any] = num_hidden_layers
UpperCamelCase__ : Union[str, Any] = intermediate_size
UpperCamelCase__ : Union[str, Any] = hidden_act
UpperCamelCase__ : List[Any] = num_attention_heads
UpperCamelCase__ : Optional[int] = hidden_dropout
UpperCamelCase__ : Tuple = attention_dropout
UpperCamelCase__ : List[Any] = activation_dropout
UpperCamelCase__ : Optional[int] = feat_proj_dropout
UpperCamelCase__ : int = final_dropout
UpperCamelCase__ : str = layerdrop
UpperCamelCase__ : Dict = layer_norm_eps
UpperCamelCase__ : str = initializer_range
UpperCamelCase__ : List[Any] = vocab_size
UpperCamelCase__ : Dict = do_stable_layer_norm
UpperCamelCase__ : Dict = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
'''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='''
''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='''
F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,'''
F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
UpperCamelCase__ : Tuple = apply_spec_augment
UpperCamelCase__ : str = mask_time_prob
UpperCamelCase__ : Tuple = mask_time_length
UpperCamelCase__ : Optional[Any] = mask_time_min_masks
UpperCamelCase__ : str = mask_feature_prob
UpperCamelCase__ : List[str] = mask_feature_length
UpperCamelCase__ : Optional[Any] = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
UpperCamelCase__ : Dict = num_codevectors_per_group
UpperCamelCase__ : Optional[int] = num_codevector_groups
UpperCamelCase__ : Dict = contrastive_logits_temperature
UpperCamelCase__ : List[Any] = feat_quantizer_dropout
UpperCamelCase__ : List[Any] = num_negatives
UpperCamelCase__ : Tuple = codevector_dim
UpperCamelCase__ : List[str] = proj_codevector_dim
UpperCamelCase__ : Tuple = diversity_loss_weight
# ctc loss
UpperCamelCase__ : List[str] = ctc_loss_reduction
UpperCamelCase__ : Optional[Any] = ctc_zero_infinity
# adapter
UpperCamelCase__ : List[Any] = add_adapter
UpperCamelCase__ : Any = adapter_kernel_size
UpperCamelCase__ : Tuple = adapter_stride
UpperCamelCase__ : Tuple = num_adapter_layers
UpperCamelCase__ : Optional[Any] = output_hidden_size or hidden_size
UpperCamelCase__ : Union[str, Any] = adapter_attn_dim
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
UpperCamelCase__ : List[str] = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
UpperCamelCase__ : Union[str, Any] = list(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = list(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = list(__SCREAMING_SNAKE_CASE )
UpperCamelCase__ : int = xvector_output_dim
@property
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 285 | 1 |
'''simple docstring'''
__UpperCamelCase : List[Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'''
def lowercase ( lowerCAmelCase : bytes):
"""simple docstring"""
if not isinstance(lowerCAmelCase , lowerCAmelCase):
_A : List[Any] = f"""a bytes-like object is required, not '{data.__class__.__name__}'"""
raise TypeError(lowerCAmelCase)
_A : List[Any] = ''''''.join(bin(lowerCAmelCase)[2:].zfill(8) for byte in data)
_A : List[str] = len(lowerCAmelCase) % 6 != 0
if padding_needed:
# The padding that will be added later
_A : Any = B'''=''' * ((6 - len(lowerCAmelCase) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(lowerCAmelCase) % 6)
else:
_A : Optional[Any] = B''''''
# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6] , 2)]
for index in range(0 , len(lowerCAmelCase) , 6)).encode()
+ padding
)
def lowercase ( lowerCAmelCase : str):
"""simple docstring"""
if not isinstance(lowerCAmelCase , lowerCAmelCase) and not isinstance(lowerCAmelCase , lowerCAmelCase):
_A : Union[str, Any] = (
'''argument should be a bytes-like object or ASCII string, '''
f"""not '{encoded_data.__class__.__name__}'"""
)
raise TypeError(lowerCAmelCase)
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if isinstance(lowerCAmelCase , lowerCAmelCase):
try:
_A : Optional[int] = encoded_data.decode('''utf-8''')
except UnicodeDecodeError:
raise ValueError('''base64 encoded data should only contain ASCII characters''')
_A : Optional[int] = encoded_data.count('''=''')
# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]), "Invalid base64 character(s) found."
else:
assert all(
char in B64_CHARSET for char in encoded_data), "Invalid base64 character(s) found."
# Check the padding
assert len(lowerCAmelCase) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
_A : int = encoded_data[:-padding]
_A : Any = ''''''.join(
bin(B64_CHARSET.index(lowerCAmelCase))[2:].zfill(6) for char in encoded_data)[: -padding * 2]
else:
_A : Optional[int] = ''''''.join(
bin(B64_CHARSET.index(lowerCAmelCase))[2:].zfill(6) for char in encoded_data)
_A : Tuple = [
int(binary_stream[index : index + 8] , 2)
for index in range(0 , len(lowerCAmelCase) , 8)
]
return bytes(lowerCAmelCase)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 714 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mvp import MvpTokenizer
__UpperCamelCase : str = logging.get_logger(__name__)
__UpperCamelCase : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
# See all MVP models at https://huggingface.co/models?filter=mvp
__UpperCamelCase : Optional[Any] = {
'''vocab_file''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''',
},
'''added_tokens.json''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''',
},
'''merges_file''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json''',
},
}
__UpperCamelCase : Tuple = {
'''RUCAIBox/mvp''': 1024,
}
class lowerCamelCase__ ( snake_case_ ):
"""simple docstring"""
__magic_name__ = VOCAB_FILES_NAMES
__magic_name__ = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ = ["""input_ids""", """attention_mask"""]
__magic_name__ = MvpTokenizer
def __init__( self , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__="replace" , UpperCAmelCase__="<s>" , UpperCAmelCase__="</s>" , UpperCAmelCase__="</s>" , UpperCAmelCase__="<s>" , UpperCAmelCase__="<unk>" , UpperCAmelCase__="<pad>" , UpperCAmelCase__="<mask>" , UpperCAmelCase__=False , UpperCAmelCase__=True , **UpperCAmelCase__ , ) -> List[Any]:
super().__init__(
UpperCAmelCase__ , UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , errors=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ , **UpperCAmelCase__ , )
_A : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('''add_prefix_space''' , UpperCAmelCase__ ) != add_prefix_space:
_A : Dict = getattr(UpperCAmelCase__ , pre_tok_state.pop('''type''' ) )
_A : List[Any] = add_prefix_space
_A : Tuple = pre_tok_class(**UpperCAmelCase__ )
_A : List[Any] = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
_A : Any = '''post_processor'''
_A : Union[str, Any] = getattr(self.backend_tokenizer , UpperCAmelCase__ , UpperCAmelCase__ )
if tokenizer_component_instance:
_A : Optional[int] = 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 : int = tuple(state['''sep'''] )
if "cls" in state:
_A : Union[str, Any] = tuple(state['''cls'''] )
_A : int = False
if state.get('''add_prefix_space''' , UpperCAmelCase__ ) != add_prefix_space:
_A : Optional[int] = add_prefix_space
_A : Union[str, Any] = True
if state.get('''trim_offsets''' , UpperCAmelCase__ ) != trim_offsets:
_A : List[str] = trim_offsets
_A : int = True
if changes_to_apply:
_A : Optional[int] = getattr(UpperCAmelCase__ , state.pop('''type''' ) )
_A : str = component_class(**UpperCAmelCase__ )
setattr(self.backend_tokenizer , UpperCAmelCase__ , UpperCAmelCase__ )
@property
def _lowerCamelCase ( self ) -> 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 _lowerCamelCase ( self , UpperCAmelCase__ ) -> Tuple:
_A : Any = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else value
_A : Any = value
def _lowerCamelCase ( self , *UpperCAmelCase__ , **UpperCAmelCase__ ) -> BatchEncoding:
_A : Optional[int] = kwargs.get('''is_split_into_words''' , UpperCAmelCase__ )
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(*UpperCAmelCase__ , **UpperCAmelCase__ )
def _lowerCamelCase ( self , *UpperCAmelCase__ , **UpperCAmelCase__ ) -> BatchEncoding:
_A : int = kwargs.get('''is_split_into_words''' , UpperCAmelCase__ )
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(*UpperCAmelCase__ , **UpperCAmelCase__ )
def _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__ = None ) -> Tuple[str]:
_A : List[Any] = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ )
return tuple(UpperCAmelCase__ )
def _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__=None ) -> Tuple:
_A : Dict = [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 _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__ = None ) -> List[int]:
_A : str = [self.sep_token_id]
_A : Tuple = [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]
| 417 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
SCREAMING_SNAKE_CASE : Optional[int] = {
"configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"],
"tokenization_roc_bert": ["RoCBertTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
pass
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE : List[Any] = [
"ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"RoCBertForCausalLM",
"RoCBertForMaskedLM",
"RoCBertForMultipleChoice",
"RoCBertForPreTraining",
"RoCBertForQuestionAnswering",
"RoCBertForSequenceClassification",
"RoCBertForTokenClassification",
"RoCBertLayer",
"RoCBertModel",
"RoCBertPreTrainedModel",
"load_tf_weights_in_roc_bert",
]
if TYPE_CHECKING:
from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
from .tokenization_roc_bert import RoCBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
raise OptionalDependencyNotAvailable()
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roc_bert import (
ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RoCBertForCausalLM,
RoCBertForMaskedLM,
RoCBertForMultipleChoice,
RoCBertForPreTraining,
RoCBertForQuestionAnswering,
RoCBertForSequenceClassification,
RoCBertForTokenClassification,
RoCBertLayer,
RoCBertModel,
RoCBertPreTrainedModel,
load_tf_weights_in_roc_bert,
)
else:
import sys
SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 257 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
class UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def UpperCamelCase ( self ):
lowercase_ :int = 1
lowercase_ :Optional[int] = 3
lowercase_ :Optional[int] = (32, 32)
lowercase_ :str = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(UpperCamelCase_ )
return image
@property
def UpperCamelCase ( self ):
torch.manual_seed(0 )
lowercase_ :Union[str, Any] = UNetaDConditionModel(
block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=UpperCamelCase_ , only_cross_attention=(True, True, False) , num_class_embeds=100 , )
return model
@property
def UpperCamelCase ( self ):
torch.manual_seed(0 )
lowercase_ :Union[str, Any] = AutoencoderKL(
block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , )
return model
@property
def UpperCamelCase ( self ):
torch.manual_seed(0 )
lowercase_ :str = 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=1000 , hidden_act='''gelu''' , projection_dim=512 , )
return CLIPTextModel(UpperCamelCase_ )
def UpperCamelCase ( self ):
lowercase_ :str = '''cpu''' # ensure determinism for the device-dependent torch.Generator
lowercase_ :Optional[int] = self.dummy_cond_unet_upscale
lowercase_ :str = DDPMScheduler()
lowercase_ :Optional[int] = DDIMScheduler(prediction_type='''v_prediction''' )
lowercase_ :Any = self.dummy_vae
lowercase_ :Optional[Any] = self.dummy_text_encoder
lowercase_ :Any = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
lowercase_ :List[Any] = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowercase_ :Any = Image.fromarray(np.uinta(UpperCamelCase_ ) ).convert('''RGB''' ).resize((64, 64) )
# make sure here that pndm scheduler skips prk
lowercase_ :Optional[Any] = StableDiffusionUpscalePipeline(
unet=UpperCamelCase_ , low_res_scheduler=UpperCamelCase_ , scheduler=UpperCamelCase_ , vae=UpperCamelCase_ , text_encoder=UpperCamelCase_ , tokenizer=UpperCamelCase_ , max_noise_level=350 , )
lowercase_ :Dict = sd_pipe.to(UpperCamelCase_ )
sd_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowercase_ :str = '''A painting of a squirrel eating a burger'''
lowercase_ :List[Any] = torch.Generator(device=UpperCamelCase_ ).manual_seed(0 )
lowercase_ :List[Any] = sd_pipe(
[prompt] , image=UpperCamelCase_ , generator=UpperCamelCase_ , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , )
lowercase_ :Tuple = output.images
lowercase_ :Dict = torch.Generator(device=UpperCamelCase_ ).manual_seed(0 )
lowercase_ :Optional[int] = sd_pipe(
[prompt] , image=UpperCamelCase_ , generator=UpperCamelCase_ , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , return_dict=UpperCamelCase_ , )[0]
lowercase_ :Dict = image[0, -3:, -3:, -1]
lowercase_ :Any = image_from_tuple[0, -3:, -3:, -1]
lowercase_ :str = low_res_image.size[0] * 4
assert image.shape == (1, expected_height_width, expected_height_width, 3)
lowercase_ :Tuple = np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCamelCase ( self ):
lowercase_ :Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator
lowercase_ :List[str] = self.dummy_cond_unet_upscale
lowercase_ :int = DDPMScheduler()
lowercase_ :Union[str, Any] = DDIMScheduler(prediction_type='''v_prediction''' )
lowercase_ :List[Any] = self.dummy_vae
lowercase_ :int = self.dummy_text_encoder
lowercase_ :Any = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
lowercase_ :Optional[Any] = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowercase_ :Any = Image.fromarray(np.uinta(UpperCamelCase_ ) ).convert('''RGB''' ).resize((64, 64) )
# make sure here that pndm scheduler skips prk
lowercase_ :List[str] = StableDiffusionUpscalePipeline(
unet=UpperCamelCase_ , low_res_scheduler=UpperCamelCase_ , scheduler=UpperCamelCase_ , vae=UpperCamelCase_ , text_encoder=UpperCamelCase_ , tokenizer=UpperCamelCase_ , max_noise_level=350 , )
lowercase_ :Dict = sd_pipe.to(UpperCamelCase_ )
sd_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowercase_ :Optional[Any] = '''A painting of a squirrel eating a burger'''
lowercase_ :Any = sd_pipe(
2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , )
lowercase_ :Dict = output.images
assert image.shape[0] == 2
lowercase_ :Union[str, Any] = torch.Generator(device=UpperCamelCase_ ).manual_seed(0 )
lowercase_ :Dict = sd_pipe(
[prompt] , image=UpperCamelCase_ , generator=UpperCamelCase_ , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , )
lowercase_ :Tuple = output.images
assert image.shape[0] == 2
@unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' )
def UpperCamelCase ( self ):
lowercase_ :int = self.dummy_cond_unet_upscale
lowercase_ :str = DDPMScheduler()
lowercase_ :List[str] = DDIMScheduler(prediction_type='''v_prediction''' )
lowercase_ :Optional[int] = self.dummy_vae
lowercase_ :List[Any] = self.dummy_text_encoder
lowercase_ :Any = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
lowercase_ :str = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowercase_ :Tuple = Image.fromarray(np.uinta(UpperCamelCase_ ) ).convert('''RGB''' ).resize((64, 64) )
# put models in fp16, except vae as it overflows in fp16
lowercase_ :Any = unet.half()
lowercase_ :Tuple = text_encoder.half()
# make sure here that pndm scheduler skips prk
lowercase_ :str = StableDiffusionUpscalePipeline(
unet=UpperCamelCase_ , low_res_scheduler=UpperCamelCase_ , scheduler=UpperCamelCase_ , vae=UpperCamelCase_ , text_encoder=UpperCamelCase_ , tokenizer=UpperCamelCase_ , max_noise_level=350 , )
lowercase_ :Any = sd_pipe.to(UpperCamelCase_ )
sd_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowercase_ :Dict = '''A painting of a squirrel eating a burger'''
lowercase_ :str = torch.manual_seed(0 )
lowercase_ :Union[str, Any] = sd_pipe(
[prompt] , image=UpperCamelCase_ , generator=UpperCamelCase_ , num_inference_steps=2 , output_type='''np''' , ).images
lowercase_ :int = low_res_image.size[0] * 4
assert image.shape == (1, expected_height_width, expected_height_width, 3)
@slow
@require_torch_gpu
class UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase ( self ):
lowercase_ :Optional[Any] = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-upscale/low_res_cat.png''' )
lowercase_ :Any = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
'''/upsampled_cat.npy''' )
lowercase_ :Optional[int] = '''stabilityai/stable-diffusion-x4-upscaler'''
lowercase_ :int = StableDiffusionUpscalePipeline.from_pretrained(UpperCamelCase_ )
pipe.to(UpperCamelCase_ )
pipe.set_progress_bar_config(disable=UpperCamelCase_ )
pipe.enable_attention_slicing()
lowercase_ :List[Any] = '''a cat sitting on a park bench'''
lowercase_ :int = torch.manual_seed(0 )
lowercase_ :Optional[Any] = pipe(
prompt=UpperCamelCase_ , image=UpperCamelCase_ , generator=UpperCamelCase_ , output_type='''np''' , )
lowercase_ :str = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 1E-3
def UpperCamelCase ( self ):
lowercase_ :Optional[int] = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-upscale/low_res_cat.png''' )
lowercase_ :Optional[int] = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
'''/upsampled_cat_fp16.npy''' )
lowercase_ :List[Any] = '''stabilityai/stable-diffusion-x4-upscaler'''
lowercase_ :Tuple = StableDiffusionUpscalePipeline.from_pretrained(
UpperCamelCase_ , torch_dtype=torch.floataa , )
pipe.to(UpperCamelCase_ )
pipe.set_progress_bar_config(disable=UpperCamelCase_ )
pipe.enable_attention_slicing()
lowercase_ :Dict = '''a cat sitting on a park bench'''
lowercase_ :Union[str, Any] = torch.manual_seed(0 )
lowercase_ :Dict = pipe(
prompt=UpperCamelCase_ , image=UpperCamelCase_ , generator=UpperCamelCase_ , output_type='''np''' , )
lowercase_ :Optional[int] = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 5E-1
def UpperCamelCase ( self ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
lowercase_ :int = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-upscale/low_res_cat.png''' )
lowercase_ :Optional[int] = '''stabilityai/stable-diffusion-x4-upscaler'''
lowercase_ :Dict = StableDiffusionUpscalePipeline.from_pretrained(
UpperCamelCase_ , torch_dtype=torch.floataa , )
pipe.to(UpperCamelCase_ )
pipe.set_progress_bar_config(disable=UpperCamelCase_ )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
lowercase_ :int = '''a cat sitting on a park bench'''
lowercase_ :int = torch.manual_seed(0 )
lowercase_ :Union[str, Any] = pipe(
prompt=UpperCamelCase_ , image=UpperCamelCase_ , generator=UpperCamelCase_ , num_inference_steps=5 , output_type='''np''' , )
lowercase_ :str = torch.cuda.max_memory_allocated()
# make sure that less than 2.9 GB is allocated
assert mem_bytes < 2.9 * 10**9
| 257 | 1 |
from __future__ import annotations
import unittest
from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import numpy
import tensorflow as tf
from transformers.models.esm.modeling_tf_esm import (
TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFEsmForMaskedLM,
TFEsmForSequenceClassification,
TFEsmForTokenClassification,
TFEsmModel,
)
class __magic_name__ :
'''simple docstring'''
def __init__( self: str , _lowerCamelCase: Optional[Any] , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = 13
SCREAMING_SNAKE_CASE_ = 7
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = 99
SCREAMING_SNAKE_CASE_ = 32
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 4
SCREAMING_SNAKE_CASE_ = 37
SCREAMING_SNAKE_CASE_ = '''gelu'''
SCREAMING_SNAKE_CASE_ = 0.1
SCREAMING_SNAKE_CASE_ = 0.1
SCREAMING_SNAKE_CASE_ = 5_12
SCREAMING_SNAKE_CASE_ = 16
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 0.02
SCREAMING_SNAKE_CASE_ = 3
SCREAMING_SNAKE_CASE_ = 4
SCREAMING_SNAKE_CASE_ = None
def _A ( self: str ):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE_ = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE_ = random_attention_mask([self.batch_size, self.seq_length] )
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.num_choices )
SCREAMING_SNAKE_CASE_ = EsmConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , )
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def _A ( self: Optional[int] ):
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def _A ( self: Optional[int] , _lowerCamelCase: Dict , _lowerCamelCase: Optional[Any] , _lowerCamelCase: Tuple , _lowerCamelCase: int , _lowerCamelCase: Dict , _lowerCamelCase: Optional[Any] ):
SCREAMING_SNAKE_CASE_ = TFEsmModel(config=_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = [input_ids, input_mask]
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _A ( self: str , _lowerCamelCase: List[Any] , _lowerCamelCase: str , _lowerCamelCase: Union[str, Any] , _lowerCamelCase: Dict , _lowerCamelCase: Any , _lowerCamelCase: Union[str, Any] , _lowerCamelCase: Union[str, Any] , _lowerCamelCase: str , ):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = TFEsmModel(config=_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''encoder_hidden_states''': encoder_hidden_states,
'''encoder_attention_mask''': encoder_attention_mask,
}
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = [input_ids, input_mask]
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase , encoder_hidden_states=_lowerCamelCase )
# Also check the case where encoder outputs are not passed
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase , attention_mask=_lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _A ( self: str , _lowerCamelCase: Union[str, Any] , _lowerCamelCase: List[str] , _lowerCamelCase: List[str] , _lowerCamelCase: List[Any] , _lowerCamelCase: str , _lowerCamelCase: Dict ):
SCREAMING_SNAKE_CASE_ = TFEsmForMaskedLM(config=_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = model([input_ids, input_mask] )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _A ( self: Dict , _lowerCamelCase: Dict , _lowerCamelCase: Optional[Any] , _lowerCamelCase: Any , _lowerCamelCase: Optional[int] , _lowerCamelCase: Tuple , _lowerCamelCase: int ):
SCREAMING_SNAKE_CASE_ = self.num_labels
SCREAMING_SNAKE_CASE_ = TFEsmForTokenClassification(config=_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _A ( self: Dict ):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_tf
class __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[Any] = (
(
TFEsmModel,
TFEsmForMaskedLM,
TFEsmForSequenceClassification,
TFEsmForTokenClassification,
)
if is_tf_available()
else ()
)
SCREAMING_SNAKE_CASE__ : str = (
{
"feature-extraction": TFEsmModel,
"fill-mask": TFEsmForMaskedLM,
"text-classification": TFEsmForSequenceClassification,
"token-classification": TFEsmForTokenClassification,
"zero-shot": TFEsmForSequenceClassification,
}
if is_tf_available()
else {}
)
SCREAMING_SNAKE_CASE__ : Optional[int] = False
SCREAMING_SNAKE_CASE__ : Any = False
def _A ( self: Any ):
SCREAMING_SNAKE_CASE_ = TFEsmModelTester(self )
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 )
def _A ( self: Optional[Any] ):
self.config_tester.run_common_tests()
def _A ( self: Tuple ):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCamelCase )
def _A ( self: Union[str, Any] ):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*_lowerCamelCase )
def _A ( self: Dict ):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase )
def _A ( self: Tuple ):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase )
@slow
def _A ( self: Union[str, Any] ):
for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE_ = TFEsmModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
@unittest.skip('''Protein models do not support embedding resizing.''' )
def _A ( self: Optional[int] ):
pass
@unittest.skip('''Protein models do not support embedding resizing.''' )
def _A ( self: Any ):
pass
def _A ( self: List[Any] ):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE_ = model_class(_lowerCamelCase )
assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer )
if model_class is TFEsmForMaskedLM:
# Output embedding test differs from the main test because they're a matrix, not a layer
SCREAMING_SNAKE_CASE_ = model.get_bias()
assert isinstance(_lowerCamelCase , _lowerCamelCase )
for k, v in name.items():
assert isinstance(_lowerCamelCase , tf.Variable )
else:
SCREAMING_SNAKE_CASE_ = model.get_output_embeddings()
assert x is None
SCREAMING_SNAKE_CASE_ = model.get_bias()
assert name is None
@require_tf
class __magic_name__ ( unittest.TestCase):
'''simple docstring'''
@slow
def _A ( self: List[Any] ):
SCREAMING_SNAKE_CASE_ = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' )
SCREAMING_SNAKE_CASE_ = tf.constant([[0, 1, 2, 3, 4, 5]] )
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )[0]
SCREAMING_SNAKE_CASE_ = [1, 6, 33]
self.assertEqual(list(output.numpy().shape ) , _lowerCamelCase )
# compare the actual values for a slice.
SCREAMING_SNAKE_CASE_ = tf.constant(
[
[
[8.92_15_18, -10.58_98_14, -6.4_67_13_07],
[-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15],
[-7.78_12_47, -13.95_15_57, -3.74_05_92],
]
] )
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) )
@slow
def _A ( self: Union[str, Any] ):
SCREAMING_SNAKE_CASE_ = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' )
SCREAMING_SNAKE_CASE_ = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] )
SCREAMING_SNAKE_CASE_ = model(_lowerCamelCase )[0]
# compare the actual values for a slice.
SCREAMING_SNAKE_CASE_ = tf.constant(
[
[
[0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39],
[0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22],
[0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28],
]
] )
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
| 703 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__SCREAMING_SNAKE_CASE =logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE ={
"""caidas/swin2sr-classicalsr-x2-64""": (
"""https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json"""
),
}
class __magic_name__ ( __UpperCAmelCase):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[Any] = "swin2sr"
SCREAMING_SNAKE_CASE__ : str = {
"hidden_size": "embed_dim",
"num_attention_heads": "num_heads",
"num_hidden_layers": "num_layers",
}
def __init__( self: Optional[int] , _lowerCamelCase: Dict=64 , _lowerCamelCase: str=1 , _lowerCamelCase: Optional[int]=3 , _lowerCamelCase: List[Any]=1_80 , _lowerCamelCase: Optional[int]=[6, 6, 6, 6, 6, 6] , _lowerCamelCase: Union[str, Any]=[6, 6, 6, 6, 6, 6] , _lowerCamelCase: Tuple=8 , _lowerCamelCase: List[Any]=2.0 , _lowerCamelCase: Dict=True , _lowerCamelCase: Dict=0.0 , _lowerCamelCase: int=0.0 , _lowerCamelCase: Optional[int]=0.1 , _lowerCamelCase: Any="gelu" , _lowerCamelCase: int=False , _lowerCamelCase: Tuple=0.02 , _lowerCamelCase: List[str]=1E-5 , _lowerCamelCase: List[Any]=2 , _lowerCamelCase: str=1.0 , _lowerCamelCase: List[Any]="1conv" , _lowerCamelCase: str="pixelshuffle" , **_lowerCamelCase: List[str] , ):
super().__init__(**_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = patch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = embed_dim
SCREAMING_SNAKE_CASE_ = depths
SCREAMING_SNAKE_CASE_ = len(_lowerCamelCase )
SCREAMING_SNAKE_CASE_ = num_heads
SCREAMING_SNAKE_CASE_ = window_size
SCREAMING_SNAKE_CASE_ = mlp_ratio
SCREAMING_SNAKE_CASE_ = qkv_bias
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = drop_path_rate
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = use_absolute_embeddings
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = upscale
SCREAMING_SNAKE_CASE_ = img_range
SCREAMING_SNAKE_CASE_ = resi_connection
SCREAMING_SNAKE_CASE_ = upsampler
| 89 | 0 |
"""simple docstring"""
def __lowerCamelCase ( __UpperCamelCase ) -> int:
"""simple docstring"""
lowerCAmelCase_ : List[str] = [0] * len(__UpperCamelCase )
lowerCAmelCase_ : Tuple = []
lowerCAmelCase_ : Optional[int] = []
lowerCAmelCase_ : List[Any] = 0
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(__UpperCamelCase ) ):
if indegree[i] == 0:
queue.append(__UpperCamelCase )
while queue:
lowerCAmelCase_ : Union[str, Any] = queue.pop(0 )
cnt += 1
topo.append(__UpperCamelCase )
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(__UpperCamelCase )
if cnt != len(__UpperCamelCase ):
print("Cycle exists" )
else:
print(__UpperCamelCase )
# Adjacency List of Graph
lowercase__ = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topological_sort(graph)
| 610 |
"""simple docstring"""
import json
import os
import unittest
from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class __lowerCamelCase ( A__ , unittest.TestCase ):
'''simple docstring'''
a_ : str = DebertaTokenizer
a_ : List[Any] = True
a_ : Optional[int] = DebertaTokenizerFast
def lowerCamelCase ( self : Dict ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCAmelCase_ : Optional[Any] = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"[UNK]",
]
lowerCAmelCase_ : Union[str, Any] = dict(zip(a_ , range(len(a_ ) ) ) )
lowerCAmelCase_ : List[str] = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
lowerCAmelCase_ : List[Any] = {"unk_token": "[UNK]"}
lowerCAmelCase_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
lowerCAmelCase_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(a_ ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(a_ ) )
def lowerCamelCase ( self : Any , **a_ : Any ):
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **a_ )
def lowerCamelCase ( self : Tuple , a_ : List[Any] ):
lowerCAmelCase_ : List[str] = "lower newer"
lowerCAmelCase_ : int = "lower newer"
return input_text, output_text
def lowerCamelCase ( self : Union[str, Any] ):
lowerCAmelCase_ : List[Any] = self.get_tokenizer()
lowerCAmelCase_ : Union[str, Any] = "lower newer"
lowerCAmelCase_ : Union[str, Any] = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
lowerCAmelCase_ : Union[str, Any] = tokenizer.tokenize(a_ )
self.assertListEqual(a_ , a_ )
lowerCAmelCase_ : Optional[int] = tokens + [tokenizer.unk_token]
lowerCAmelCase_ : Optional[Any] = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , a_ )
def lowerCamelCase ( self : Union[str, Any] ):
lowerCAmelCase_ : Any = self.get_tokenizer()
lowerCAmelCase_ : List[Any] = tokenizer("Hello" , "World" )
lowerCAmelCase_ : Dict = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
self.assertListEqual(tokd["token_type_ids"] , a_ )
@slow
def lowerCamelCase ( self : Tuple ):
lowerCAmelCase_ : Any = self.tokenizer_class.from_pretrained("microsoft/deberta-base" )
lowerCAmelCase_ : int = tokenizer.encode("sequence builders" , add_special_tokens=a_ )
lowerCAmelCase_ : int = tokenizer.encode("multi-sequence build" , add_special_tokens=a_ )
lowerCAmelCase_ : str = tokenizer.encode(
"sequence builders" , add_special_tokens=a_ , add_prefix_space=a_ )
lowerCAmelCase_ : int = tokenizer.encode(
"sequence builders" , "multi-sequence build" , add_special_tokens=a_ , add_prefix_space=a_ )
lowerCAmelCase_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(a_ )
lowerCAmelCase_ : List[str] = tokenizer.build_inputs_with_special_tokens(a_ , a_ )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
@slow
def lowerCamelCase ( self : str ):
lowerCAmelCase_ : str = [self.tokenizer_class]
if self.test_rust_tokenizer:
tokenizer_classes.append(self.rust_tokenizer_class )
for tokenizer_class in tokenizer_classes:
lowerCAmelCase_ : Union[str, Any] = tokenizer_class.from_pretrained("microsoft/deberta-base" )
lowerCAmelCase_ : Dict = [
"ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
"ALBERT incorporates two parameter reduction techniques",
"The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
" embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
" vocabulary embedding.",
]
lowerCAmelCase_ : int = tokenizer(a_ , padding=a_ )
lowerCAmelCase_ : Tuple = [tokenizer.decode(a_ , skip_special_tokens=a_ ) for seq in encoding["input_ids"]]
# fmt: off
lowerCAmelCase_ : Optional[int] = {
"input_ids": [
[1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2]
],
"token_type_ids": [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
],
"attention_mask": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
}
# fmt: on
lowerCAmelCase_ : Tuple = [
"ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
"ALBERT incorporates two parameter reduction techniques",
"The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
" embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
" vocabulary embedding.",
]
self.assertDictEqual(encoding.data , a_ )
for expected, decoded in zip(a_ , a_ ):
self.assertEqual(a_ , a_ )
| 610 | 1 |
import argparse
import collections
import os
import re
import tempfile
import pandas as pd
from datasets import Dataset
from huggingface_hub import hf_hub_download, upload_folder
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/update_metadata.py
__lowerCAmelCase : Dict ='src/transformers'
# This is to make sure the transformers module imported is the one in the repo.
__lowerCAmelCase : Optional[Any] =direct_transformers_import(TRANSFORMERS_PATH)
# Regexes that match TF/Flax/PT model names.
__lowerCAmelCase : Any =re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
__lowerCAmelCase : Union[str, Any] =re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
__lowerCAmelCase : Optional[int] =re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Fill this with tuples (pipeline_tag, model_mapping, auto_model)
__lowerCAmelCase : List[str] =[
('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'),
('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'),
('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'),
('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'),
('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'),
('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'),
('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'),
('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'),
('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'),
(
'zero-shot-object-detection',
'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES',
'AutoModelForZeroShotObjectDetection',
),
('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'),
('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'),
('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'),
('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'),
(
'table-question-answering',
'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES',
'AutoModelForTableQuestionAnswering',
),
('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'),
('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'),
(
'next-sentence-prediction',
'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES',
'AutoModelForNextSentencePrediction',
),
(
'audio-frame-classification',
'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES',
'AutoModelForAudioFrameClassification',
),
('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'),
(
'document-question-answering',
'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES',
'AutoModelForDocumentQuestionAnswering',
),
(
'visual-question-answering',
'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES',
'AutoModelForVisualQuestionAnswering',
),
('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'),
(
'zero-shot-image-classification',
'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES',
'AutoModelForZeroShotImageClassification',
),
('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'),
('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'),
('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'),
]
def _UpperCamelCase ( lowercase__ ):
__SCREAMING_SNAKE_CASE : Optional[Any] = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , lowercase__ )
return [m.group(0 ) for m in matches]
def _UpperCamelCase ( ):
__SCREAMING_SNAKE_CASE : List[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
__SCREAMING_SNAKE_CASE : List[str] = {
config.replace('''Config''' , '''''' ): model_type for model_type, config in config_maping_names.items()
}
# Dictionaries flagging if each model prefix has a backend in PT/TF/Flax.
__SCREAMING_SNAKE_CASE : int = collections.defaultdict(lowercase__ )
__SCREAMING_SNAKE_CASE : int = collections.defaultdict(lowercase__ )
__SCREAMING_SNAKE_CASE : Tuple = collections.defaultdict(lowercase__ )
# Let's lookup through all transformers object (once) and find if models are supported by a given backend.
for attr_name in dir(lowercase__ ):
__SCREAMING_SNAKE_CASE : Dict = None
if _re_tf_models.match(lowercase__ ) is not None:
__SCREAMING_SNAKE_CASE : Any = tf_models
__SCREAMING_SNAKE_CASE : Optional[Any] = _re_tf_models.match(lowercase__ ).groups()[0]
elif _re_flax_models.match(lowercase__ ) is not None:
__SCREAMING_SNAKE_CASE : List[str] = flax_models
__SCREAMING_SNAKE_CASE : str = _re_flax_models.match(lowercase__ ).groups()[0]
elif _re_pt_models.match(lowercase__ ) is not None:
__SCREAMING_SNAKE_CASE : int = pt_models
__SCREAMING_SNAKE_CASE : List[str] = _re_pt_models.match(lowercase__ ).groups()[0]
if lookup_dict is not None:
while len(lowercase__ ) > 0:
if attr_name in model_prefix_to_model_type:
__SCREAMING_SNAKE_CASE : Any = True
break
# Try again after removing the last word in the name
__SCREAMING_SNAKE_CASE : List[Any] = ''''''.join(camel_case_split(lowercase__ )[:-1] )
__SCREAMING_SNAKE_CASE : Dict = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) )
__SCREAMING_SNAKE_CASE : Optional[Any] = list(lowercase__ )
all_models.sort()
__SCREAMING_SNAKE_CASE : Tuple = {'''model_type''': all_models}
__SCREAMING_SNAKE_CASE : str = [pt_models[t] for t in all_models]
__SCREAMING_SNAKE_CASE : Optional[int] = [tf_models[t] for t in all_models]
__SCREAMING_SNAKE_CASE : Any = [flax_models[t] for t in all_models]
# Now let's use the auto-mapping names to make sure
__SCREAMING_SNAKE_CASE : List[Any] = {}
for t in all_models:
if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES:
__SCREAMING_SNAKE_CASE : Any = '''AutoProcessor'''
elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES:
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''AutoTokenizer'''
elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES:
__SCREAMING_SNAKE_CASE : Dict = '''AutoFeatureExtractor'''
else:
# Default to AutoTokenizer if a model has nothing, for backward compatibility.
__SCREAMING_SNAKE_CASE : Any = '''AutoTokenizer'''
__SCREAMING_SNAKE_CASE : List[str] = [processors[t] for t in all_models]
return pd.DataFrame(lowercase__ )
def _UpperCamelCase ( lowercase__ ):
__SCREAMING_SNAKE_CASE : int = [
transformers_module.models.auto.modeling_auto,
transformers_module.models.auto.modeling_tf_auto,
transformers_module.models.auto.modeling_flax_auto,
]
for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS:
__SCREAMING_SNAKE_CASE : List[Any] = [model_mapping, F'''TF_{model_mapping}''', F'''FLAX_{model_mapping}''']
__SCREAMING_SNAKE_CASE : List[Any] = [auto_class, F'''TF_{auto_class}''', F'''Flax_{auto_class}''']
# Loop through all three frameworks
for module, cls, mapping in zip(lowercase__ , lowercase__ , lowercase__ ):
# The type of pipeline may not exist in this framework
if not hasattr(lowercase__ , lowercase__ ):
continue
# First extract all model_names
__SCREAMING_SNAKE_CASE : Union[str, Any] = []
for name in getattr(lowercase__ , lowercase__ ).values():
if isinstance(lowercase__ , lowercase__ ):
model_names.append(lowercase__ )
else:
model_names.extend(list(lowercase__ ) )
# Add pipeline tag and auto model class for those models
table.update({model_name: (pipeline_tag, cls) for model_name in model_names} )
return table
def _UpperCamelCase ( lowercase__ , lowercase__ ):
__SCREAMING_SNAKE_CASE : List[Any] = get_frameworks_table()
__SCREAMING_SNAKE_CASE : Any = Dataset.from_pandas(lowercase__ )
__SCREAMING_SNAKE_CASE : int = hf_hub_download(
'''huggingface/transformers-metadata''' , '''pipeline_tags.json''' , repo_type='''dataset''' , token=lowercase__ )
__SCREAMING_SNAKE_CASE : Any = Dataset.from_json(lowercase__ )
__SCREAMING_SNAKE_CASE : List[str] = {
tags_dataset[i]['''model_class''']: (tags_dataset[i]['''pipeline_tag'''], tags_dataset[i]['''auto_class'''])
for i in range(len(lowercase__ ) )
}
__SCREAMING_SNAKE_CASE : Optional[Any] = update_pipeline_and_auto_class_table(lowercase__ )
# Sort the model classes to avoid some nondeterministic updates to create false update commits.
__SCREAMING_SNAKE_CASE : List[str] = sorted(table.keys() )
__SCREAMING_SNAKE_CASE : Union[str, Any] = pd.DataFrame(
{
'''model_class''': model_classes,
'''pipeline_tag''': [table[m][0] for m in model_classes],
'''auto_class''': [table[m][1] for m in model_classes],
} )
__SCREAMING_SNAKE_CASE : List[str] = Dataset.from_pandas(lowercase__ )
with tempfile.TemporaryDirectory() as tmp_dir:
frameworks_dataset.to_json(os.path.join(lowercase__ , '''frameworks.json''' ) )
tags_dataset.to_json(os.path.join(lowercase__ , '''pipeline_tags.json''' ) )
if commit_sha is not None:
__SCREAMING_SNAKE_CASE : Any = (
F'''Update with commit {commit_sha}\n\nSee: '''
F'''https://github.com/huggingface/transformers/commit/{commit_sha}'''
)
else:
__SCREAMING_SNAKE_CASE : Optional[Any] = '''Update'''
upload_folder(
repo_id='''huggingface/transformers-metadata''' , folder_path=lowercase__ , repo_type='''dataset''' , token=lowercase__ , commit_message=lowercase__ , )
def _UpperCamelCase ( ):
__SCREAMING_SNAKE_CASE : List[str] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS}
__SCREAMING_SNAKE_CASE : Any = transformers_module.pipelines.SUPPORTED_TASKS
__SCREAMING_SNAKE_CASE : List[Any] = []
for key in pipeline_tasks:
if key not in in_table:
__SCREAMING_SNAKE_CASE : Any = pipeline_tasks[key]['''pt''']
if isinstance(lowercase__ , (list, tuple) ):
__SCREAMING_SNAKE_CASE : Dict = model[0]
__SCREAMING_SNAKE_CASE : Any = model.__name__
if model not in in_table.values():
missing.append(lowercase__ )
if len(lowercase__ ) > 0:
__SCREAMING_SNAKE_CASE : Dict = ''', '''.join(lowercase__ )
raise ValueError(
'''The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside '''
F'''`utils/update_metadata.py`: {msg}. Please add them!''' )
if __name__ == "__main__":
__lowerCAmelCase : Dict =argparse.ArgumentParser()
parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.')
parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.')
parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.')
__lowerCAmelCase : Tuple =parser.parse_args()
if args.check_only:
check_pipeline_tags()
else:
update_metadata(args.token, args.commit_sha)
| 260 |
class _lowercase :
'''simple docstring'''
def __init__( self :Any , lowerCAmelCase__ :list[int] ) -> None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = len(lowerCAmelCase__ )
__SCREAMING_SNAKE_CASE : List[Any] = [0] * len_array
if len_array > 0:
__SCREAMING_SNAKE_CASE : List[Any] = array[0]
for i in range(1 , lowerCAmelCase__ ):
__SCREAMING_SNAKE_CASE : List[str] = self.prefix_sum[i - 1] + array[i]
def __magic_name__( self :Any , lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> int:
if start == 0:
return self.prefix_sum[end]
return self.prefix_sum[end] - self.prefix_sum[start - 1]
def __magic_name__( self :List[Any] , lowerCAmelCase__ :int ) -> bool:
__SCREAMING_SNAKE_CASE : Optional[Any] = {0}
for sum_item in self.prefix_sum:
if sum_item - target_sum in sums:
return True
sums.add(lowerCAmelCase__ )
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 260 | 1 |
'''simple docstring'''
from datetime import datetime
import requests
from bsa import BeautifulSoup
if __name__ == "__main__":
lowerCAmelCase : Optional[Any] = input("""Enter image url: """).strip()
print(F'''Downloading image from {url} ...''')
lowerCAmelCase : str = BeautifulSoup(requests.get(url).content, """html.parser""")
# The image URL is in the content field of the first meta tag with property og:image
lowerCAmelCase : Any = soup.find("""meta""", {"""property""": """og:image"""})["""content"""]
lowerCAmelCase : Optional[Any] = requests.get(image_url).content
lowerCAmelCase : Tuple = F'''{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg'''
with open(file_name, """wb""") as fp:
fp.write(image_data)
print(F'''Done. Image saved to disk as {file_name}.''')
| 372 |
'''simple docstring'''
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConformerConfig,
WavaVecaConformerForCTC,
WavaVecaConformerForPreTraining,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
lowerCAmelCase : int = logging.get_logger(__name__)
lowerCAmelCase : Dict = {
"""post_extract_proj""": """feature_projection.projection""",
"""encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
"""self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""",
"""self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""",
"""self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""",
"""self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""",
"""self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""",
"""self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""",
"""self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""",
"""self_attn.rotary_emb""": """encoder.embed_positions""",
"""self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""",
"""conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""",
"""conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""",
"""conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""",
"""conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""",
"""conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""",
"""ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""",
"""ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""",
"""ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""",
"""ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""",
"""ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""",
"""ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""",
"""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""",
}
lowerCAmelCase : Optional[Any] = [
"""lm_head""",
"""quantizer.weight_proj""",
"""quantizer.codevectors""",
"""project_q""",
"""project_hid""",
]
def _A ( A ,A ,A ,A ,A ) -> Tuple:
for attribute in key.split("." ):
lowercase : Dict = getattr(A ,A )
if weight_type is not None:
lowercase : List[str] = getattr(A ,A ).shape
else:
lowercase : Any = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}''' )
if weight_type == "weight":
lowercase : List[Any] = value
elif weight_type == "weight_g":
lowercase : List[Any] = value
elif weight_type == "weight_v":
lowercase : int = value
elif weight_type == "bias":
lowercase : Any = value
elif weight_type == "running_mean":
lowercase : Tuple = value
elif weight_type == "running_var":
lowercase : Dict = value
elif weight_type == "num_batches_tracked":
lowercase : Optional[int] = value
elif weight_type == "inv_freq":
lowercase : List[Any] = value
else:
lowercase : Dict = value
logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' )
def _A ( A ,A ,A ) -> int:
lowercase : Optional[int] = []
lowercase : Tuple = fairseq_model.state_dict()
lowercase : Optional[Any] = hf_model.wavaveca_conformer.feature_extractor
for name, value in fairseq_dict.items():
lowercase : str = False
if "conv_layers" in name:
load_conv_layer(
A ,A ,A ,A ,hf_model.config.feat_extract_norm == "group" ,)
lowercase : Dict = True
else:
for key, mapped_key in MAPPING.items():
lowercase : List[str] = "wav2vec2_conformer." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]:
lowercase : List[str] = True
if "*" in mapped_key:
lowercase : int = name.split(A )[0].split("." )[-2]
lowercase : Optional[Any] = mapped_key.replace("*" ,A )
if "pos_bias_u" in name:
lowercase : str = None
elif "pos_bias_v" in name:
lowercase : Optional[int] = None
elif "weight_g" in name:
lowercase : int = "weight_g"
elif "weight_v" in name:
lowercase : Dict = "weight_v"
elif "bias" in name:
lowercase : List[str] = "bias"
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
lowercase : Optional[int] = "weight"
elif "running_mean" in name:
lowercase : Optional[int] = "running_mean"
elif "inv_freq" in name:
lowercase : Dict = "inv_freq"
elif "running_var" in name:
lowercase : int = "running_var"
elif "num_batches_tracked" in name:
lowercase : Optional[Any] = "num_batches_tracked"
else:
lowercase : int = None
set_recursively(A ,A ,A ,A ,A )
continue
if not is_used:
unused_weights.append(A )
logger.warning(F'''Unused weights: {unused_weights}''' )
def _A ( A ,A ,A ,A ,A ) -> List[str]:
lowercase : Tuple = full_name.split("conv_layers." )[-1]
lowercase : Optional[Any] = name.split("." )
lowercase : str = int(items[0] )
lowercase : List[Any] = int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' )
lowercase : Union[str, Any] = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' )
lowercase : str = 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:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' )
lowercase : int = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' )
lowercase : str = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(A )
@torch.no_grad()
def _A ( A ,A ,A=None ,A=None ,A=True ) -> Optional[Any]:
if config_path is not None:
lowercase : Tuple = WavaVecaConformerConfig.from_pretrained(A ,hidden_act="swish" )
else:
lowercase : Any = WavaVecaConformerConfig()
if "rope" in checkpoint_path:
lowercase : str = "rotary"
if is_finetuned:
if dict_path:
lowercase : List[str] = Dictionary.load(A )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
lowercase : Optional[int] = target_dict.pad_index
lowercase : Optional[int] = target_dict.bos_index
lowercase : Optional[Any] = target_dict.eos_index
lowercase : str = len(target_dict.symbols )
lowercase : List[Any] = os.path.join(A ,"vocab.json" )
if not os.path.isdir(A ):
logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(A ) )
return
os.makedirs(A ,exist_ok=A )
lowercase : Any = target_dict.indices
# fairseq has the <pad> and <s> switched
lowercase : Any = 0
lowercase : Tuple = 1
with open(A ,"w" ,encoding="utf-8" ) as vocab_handle:
json.dump(A ,A )
lowercase : Tuple = WavaVecaCTCTokenizer(
A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="|" ,do_lower_case=A ,)
lowercase : Dict = True if config.feat_extract_norm == "layer" else False
lowercase : List[str] = WavaVecaFeatureExtractor(
feature_size=1 ,sampling_rate=1_6_0_0_0 ,padding_value=0 ,do_normalize=A ,return_attention_mask=A ,)
lowercase : List[str] = WavaVecaProcessor(feature_extractor=A ,tokenizer=A )
processor.save_pretrained(A )
lowercase : Any = WavaVecaConformerForCTC(A )
else:
lowercase : str = WavaVecaConformerForPreTraining(A )
if is_finetuned:
lowercase , lowercase , lowercase : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] ,arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} )
else:
lowercase : List[str] = argparse.Namespace(task="audio_pretraining" )
lowercase : Union[str, Any] = fairseq.tasks.setup_task(A )
lowercase , lowercase , lowercase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=A )
lowercase : List[str] = model[0].eval()
recursively_load_weights(A ,A ,not is_finetuned )
hf_wavavec.save_pretrained(A )
if __name__ == "__main__":
lowerCAmelCase : str = 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("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
parser.add_argument(
"""--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
)
lowerCAmelCase : int = parser.parse_args()
convert_wavaveca_conformer_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 372 | 1 |
import argparse
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
if __name__ == "__main__":
snake_case = argparse.ArgumentParser()
parser.add_argument(
"""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert."""
)
parser.add_argument(
"""--original_config_file""",
type=str,
required=True,
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(
"""--image_size""",
default=5_1_2,
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(
"""--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.)""")
def SCREAMING_SNAKE_CASE__ ( snake_case__ :Optional[Any] ) -> Dict:
if string == "True":
return True
elif string == "False":
return False
else:
raise ValueError(F"""could not parse string as bool {string}""" )
parser.add_argument(
"""--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool
)
parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int)
snake_case = parser.parse_args()
snake_case = download_controlnet_from_original_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
extract_ema=args.extract_ema,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
use_linear_projection=args.use_linear_projection,
cross_attention_dim=args.cross_attention_dim,
)
controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) | 535 |
snake_case = 8.3_144_598
def SCREAMING_SNAKE_CASE__ ( snake_case__ :float , snake_case__ :float ) -> float:
if temperature < 0:
raise Exception('Temperature cannot be less than 0 K' )
if molar_mass <= 0:
raise Exception('Molar mass cannot be less than or equal to 0 kg/mol' )
else:
return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5
if __name__ == "__main__":
import doctest
# run doctest
doctest.testmod()
# example
snake_case = 3_0_0
snake_case = 2_8
snake_case = rms_speed_of_molecule(temperature, molar_mass)
print(F"""Vrms of Nitrogen gas at 300 K is {vrms} m/s""") | 535 | 1 |
import argparse
import json
import os
import pickle
import shutil
import numpy as np
import torch
from distiller import Distiller
from lm_seqs_dataset import LmSeqsDataset
from transformers import (
BertConfig,
BertForMaskedLM,
BertTokenizer,
DistilBertConfig,
DistilBertForMaskedLM,
DistilBertTokenizer,
GPTaConfig,
GPTaLMHeadModel,
GPTaTokenizer,
RobertaConfig,
RobertaForMaskedLM,
RobertaTokenizer,
)
from utils import git_log, init_gpu_params, logger, set_seed
A : int = {
'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer),
'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer),
'bert': (BertConfig, BertForMaskedLM, BertTokenizer),
'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer),
}
def UpperCamelCase ( __magic_name__ : List[str] ) -> Union[str, Any]:
"""simple docstring"""
assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0)
assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0)
if args.mlm:
assert os.path.isfile(args.token_counts )
assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"])
else:
assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"])
assert args.teacher_type == args.student_type or (
args.student_type == "distilbert" and args.teacher_type == "bert"
)
assert os.path.isfile(args.student_config )
if args.student_pretrained_weights is not None:
assert os.path.isfile(args.student_pretrained_weights )
if args.freeze_token_type_embds:
assert args.student_type in ["roberta"]
assert args.alpha_ce >= 0.0
assert args.alpha_mlm >= 0.0
assert args.alpha_clm >= 0.0
assert args.alpha_mse >= 0.0
assert args.alpha_cos >= 0.0
assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0
def UpperCamelCase ( __magic_name__ : int , __magic_name__ : str ) -> Optional[int]:
"""simple docstring"""
if args.student_type == "roberta":
lowercase__ = False
elif args.student_type == "gpt2":
lowercase__ = False
def UpperCamelCase ( __magic_name__ : Tuple , __magic_name__ : Tuple ) -> Tuple:
"""simple docstring"""
if args.student_type == "roberta":
lowercase__ = False
def UpperCamelCase ( ) -> str:
"""simple docstring"""
lowercase__ = argparse.ArgumentParser(description="""Training""" )
parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" )
parser.add_argument(
"""--dump_path""" , type=__magic_name__ , required=__magic_name__ , help="""The output directory (log, checkpoints, parameters, etc.)""" )
parser.add_argument(
"""--data_file""" , type=__magic_name__ , required=__magic_name__ , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , )
parser.add_argument(
"""--student_type""" , type=__magic_name__ , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__magic_name__ , help="""The student type (DistilBERT, RoBERTa).""" , )
parser.add_argument("""--student_config""" , type=__magic_name__ , required=__magic_name__ , help="""Path to the student configuration.""" )
parser.add_argument(
"""--student_pretrained_weights""" , default=__magic_name__ , type=__magic_name__ , help="""Load student initialization checkpoint.""" )
parser.add_argument(
"""--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__magic_name__ , help="""Teacher type (BERT, RoBERTa).""" )
parser.add_argument("""--teacher_name""" , type=__magic_name__ , required=__magic_name__ , help="""The teacher model.""" )
parser.add_argument("""--temperature""" , default=2.0 , type=__magic_name__ , help="""Temperature for the softmax temperature.""" )
parser.add_argument(
"""--alpha_ce""" , default=0.5 , type=__magic_name__ , help="""Linear weight for the distillation loss. Must be >=0.""" )
parser.add_argument(
"""--alpha_mlm""" , default=0.0 , type=__magic_name__ , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , )
parser.add_argument("""--alpha_clm""" , default=0.5 , type=__magic_name__ , help="""Linear weight for the CLM loss. Must be >=0.""" )
parser.add_argument("""--alpha_mse""" , default=0.0 , type=__magic_name__ , help="""Linear weight of the MSE loss. Must be >=0.""" )
parser.add_argument(
"""--alpha_cos""" , default=0.0 , type=__magic_name__ , help="""Linear weight of the cosine embedding loss. Must be >=0.""" )
parser.add_argument(
"""--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" )
parser.add_argument(
"""--mlm_mask_prop""" , default=0.1_5 , type=__magic_name__ , help="""Proportion of tokens for which we need to make a prediction.""" , )
parser.add_argument("""--word_mask""" , default=0.8 , type=__magic_name__ , help="""Proportion of tokens to mask out.""" )
parser.add_argument("""--word_keep""" , default=0.1 , type=__magic_name__ , help="""Proportion of tokens to keep.""" )
parser.add_argument("""--word_rand""" , default=0.1 , type=__magic_name__ , help="""Proportion of tokens to randomly replace.""" )
parser.add_argument(
"""--mlm_smoothing""" , default=0.7 , type=__magic_name__ , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , )
parser.add_argument("""--token_counts""" , type=__magic_name__ , help="""The token counts in the data_file for MLM.""" )
parser.add_argument(
"""--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , )
parser.add_argument(
"""--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , )
parser.add_argument(
"""--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , )
parser.add_argument("""--n_epoch""" , type=__magic_name__ , default=3 , help="""Number of pass on the whole dataset.""" )
parser.add_argument("""--batch_size""" , type=__magic_name__ , default=5 , help="""Batch size (for each process).""" )
parser.add_argument(
"""--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , )
parser.add_argument(
"""--gradient_accumulation_steps""" , type=__magic_name__ , default=50 , help="""Gradient accumulation for larger training batches.""" , )
parser.add_argument("""--warmup_prop""" , default=0.0_5 , type=__magic_name__ , help="""Linear warmup proportion.""" )
parser.add_argument("""--weight_decay""" , default=0.0 , type=__magic_name__ , help="""Weight decay if we apply some.""" )
parser.add_argument("""--learning_rate""" , default=5E-4 , type=__magic_name__ , help="""The initial learning rate for Adam.""" )
parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__magic_name__ , help="""Epsilon for Adam optimizer.""" )
parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__magic_name__ , help="""Max gradient norm.""" )
parser.add_argument("""--initializer_range""" , default=0.0_2 , type=__magic_name__ , help="""Random initialization range.""" )
parser.add_argument(
"""--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , )
parser.add_argument(
"""--fp16_opt_level""" , type=__magic_name__ , default="""O1""" , help=(
"""For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."""
"""See details at https://nvidia.github.io/apex/amp.html"""
) , )
parser.add_argument("""--n_gpu""" , type=__magic_name__ , default=1 , help="""Number of GPUs in the node.""" )
parser.add_argument("""--local_rank""" , type=__magic_name__ , default=-1 , help="""Distributed training - Local rank""" )
parser.add_argument("""--seed""" , type=__magic_name__ , default=56 , help="""Random seed""" )
parser.add_argument("""--log_interval""" , type=__magic_name__ , default=500 , help="""Tensorboard logging interval.""" )
parser.add_argument("""--checkpoint_interval""" , type=__magic_name__ , default=4000 , help="""Checkpoint interval.""" )
lowercase__ = parser.parse_args()
sanity_checks(__magic_name__ )
# ARGS #
init_gpu_params(__magic_name__ )
set_seed(__magic_name__ )
if args.is_master:
if os.path.exists(args.dump_path ):
if not args.force:
raise ValueError(
f'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite'''
""" itUse `--force` if you want to overwrite it""" )
else:
shutil.rmtree(args.dump_path )
if not os.path.exists(args.dump_path ):
os.makedirs(args.dump_path )
logger.info(f'''Experiment will be dumped and logged in {args.dump_path}''' )
# SAVE PARAMS #
logger.info(f'''Param: {args}''' )
with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f:
json.dump(vars(__magic_name__ ) , __magic_name__ , indent=4 )
git_log(args.dump_path )
lowercase__ , lowercase__ , lowercase__ = MODEL_CLASSES[args.student_type]
lowercase__ , lowercase__ , lowercase__ = MODEL_CLASSES[args.teacher_type]
# TOKENIZER #
lowercase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name )
lowercase__ = {}
for tok_name, tok_symbol in tokenizer.special_tokens_map.items():
lowercase__ = tokenizer.all_special_tokens.index(__magic_name__ )
lowercase__ = tokenizer.all_special_ids[idx]
logger.info(f'''Special tokens {special_tok_ids}''' )
lowercase__ = special_tok_ids
lowercase__ = tokenizer.max_model_input_sizes[args.teacher_name]
# DATA LOADER #
logger.info(f'''Loading data from {args.data_file}''' )
with open(args.data_file , """rb""" ) as fp:
lowercase__ = pickle.load(__magic_name__ )
if args.mlm:
logger.info(f'''Loading token counts from {args.token_counts} (already pre-computed)''' )
with open(args.token_counts , """rb""" ) as fp:
lowercase__ = pickle.load(__magic_name__ )
lowercase__ = np.maximum(__magic_name__ , 1 ) ** -args.mlm_smoothing
for idx in special_tok_ids.values():
lowercase__ = 0.0 # do not predict special tokens
lowercase__ = torch.from_numpy(__magic_name__ )
else:
lowercase__ = None
lowercase__ = LmSeqsDataset(params=__magic_name__ , data=__magic_name__ )
logger.info("""Data loader created.""" )
# STUDENT #
logger.info(f'''Loading student config from {args.student_config}''' )
lowercase__ = student_config_class.from_pretrained(args.student_config )
lowercase__ = True
if args.student_pretrained_weights is not None:
logger.info(f'''Loading pretrained weights from {args.student_pretrained_weights}''' )
lowercase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__magic_name__ )
else:
lowercase__ = student_model_class(__magic_name__ )
if args.n_gpu > 0:
student.to(f'''cuda:{args.local_rank}''' )
logger.info("""Student loaded.""" )
# TEACHER #
lowercase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__magic_name__ )
if args.n_gpu > 0:
teacher.to(f'''cuda:{args.local_rank}''' )
logger.info(f'''Teacher loaded from {args.teacher_name}.''' )
# FREEZING #
if args.freeze_pos_embs:
freeze_pos_embeddings(__magic_name__ , __magic_name__ )
if args.freeze_token_type_embds:
freeze_token_type_embeddings(__magic_name__ , __magic_name__ )
# SANITY CHECKS #
assert student.config.vocab_size == teacher.config.vocab_size
assert student.config.hidden_size == teacher.config.hidden_size
assert student.config.max_position_embeddings == teacher.config.max_position_embeddings
if args.mlm:
assert token_probs.size(0 ) == stu_architecture_config.vocab_size
# DISTILLER #
torch.cuda.empty_cache()
lowercase__ = Distiller(
params=__magic_name__ , dataset=__magic_name__ , token_probs=__magic_name__ , student=__magic_name__ , teacher=__magic_name__ )
distiller.train()
logger.info("""Let's go get some drinks.""" )
if __name__ == "__main__":
main()
| 15 |
"""simple docstring"""
import math
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from .attention_processor import Attention
from .embeddings import get_timestep_embedding
from .modeling_utils import ModelMixin
class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
@register_to_config
def __init__( self , _lowercase = 1_2_8 , _lowercase = 2_5_6 , _lowercase = 2000.0 , _lowercase = 7_6_8 , _lowercase = 1_2 , _lowercase = 1_2 , _lowercase = 6_4 , _lowercase = 2_0_4_8 , _lowercase = 0.1 , ) -> Dict:
'''simple docstring'''
super().__init__()
snake_case_ : Optional[Any] = nn.Sequential(
nn.Linear(_lowercase , d_model * 4 , bias=_lowercase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=_lowercase ) , nn.SiLU() , )
snake_case_ : Any = nn.Embedding(_lowercase , _lowercase )
snake_case_ : Union[str, Any] = False
snake_case_ : List[Any] = nn.Linear(_lowercase , _lowercase , bias=_lowercase )
snake_case_ : Union[str, Any] = nn.Dropout(p=_lowercase )
snake_case_ : Tuple = nn.ModuleList()
for lyr_num in range(_lowercase ):
# FiLM conditional T5 decoder
snake_case_ : Union[str, Any] = DecoderLayer(d_model=_lowercase , d_kv=_lowercase , num_heads=_lowercase , d_ff=_lowercase , dropout_rate=_lowercase )
self.decoders.append(_lowercase )
snake_case_ : List[Any] = TaLayerNorm(_lowercase )
snake_case_ : Optional[Any] = nn.Dropout(p=_lowercase )
snake_case_ : List[Any] = nn.Linear(_lowercase , _lowercase , bias=_lowercase )
def UpperCAmelCase__ ( self , _lowercase , _lowercase ) -> Optional[Any]:
'''simple docstring'''
snake_case_ : Optional[int] = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) )
return mask.unsqueeze(-3 )
def UpperCAmelCase__ ( self , _lowercase , _lowercase , _lowercase ) -> List[Any]:
'''simple docstring'''
snake_case_ , snake_case_ , snake_case_ : str = decoder_input_tokens.shape
assert decoder_noise_time.shape == (batch,)
# decoder_noise_time is in [0, 1), so rescale to expected timing range.
snake_case_ : Optional[int] = get_timestep_embedding(
decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype )
snake_case_ : int = self.conditioning_emb(_lowercase ).unsqueeze(1 )
assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)
snake_case_ : Tuple = decoder_input_tokens.shape[1]
# If we want to use relative positions for audio context, we can just offset
# this sequence by the length of encodings_and_masks.
snake_case_ : Dict = torch.broadcast_to(
torch.arange(_lowercase , device=decoder_input_tokens.device ) , (batch, seq_length) , )
snake_case_ : Tuple = self.position_encoding(_lowercase )
snake_case_ : Optional[Any] = self.continuous_inputs_projection(_lowercase )
inputs += position_encodings
snake_case_ : List[Any] = self.dropout(_lowercase )
# decoder: No padding present.
snake_case_ : Tuple = torch.ones(
decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype )
# Translate encoding masks to encoder-decoder masks.
snake_case_ : int = [(x, self.encoder_decoder_mask(_lowercase , _lowercase )) for x, y in encodings_and_masks]
# cross attend style: concat encodings
snake_case_ : Optional[Any] = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 )
snake_case_ : str = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 )
for lyr in self.decoders:
snake_case_ : int = lyr(
_lowercase , conditioning_emb=_lowercase , encoder_hidden_states=_lowercase , encoder_attention_mask=_lowercase , )[0]
snake_case_ : int = self.decoder_norm(_lowercase )
snake_case_ : Union[str, Any] = self.post_dropout(_lowercase )
snake_case_ : int = self.spec_out(_lowercase )
return spec_out
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase=1E-6 ) -> Union[str, Any]:
'''simple docstring'''
super().__init__()
snake_case_ : Any = nn.ModuleList()
# cond self attention: layer 0
self.layer.append(
TaLayerSelfAttentionCond(d_model=_lowercase , d_kv=_lowercase , num_heads=_lowercase , dropout_rate=_lowercase ) )
# cross attention: layer 1
self.layer.append(
TaLayerCrossAttention(
d_model=_lowercase , d_kv=_lowercase , num_heads=_lowercase , dropout_rate=_lowercase , layer_norm_epsilon=_lowercase , ) )
# Film Cond MLP + dropout: last layer
self.layer.append(
TaLayerFFCond(d_model=_lowercase , d_ff=_lowercase , dropout_rate=_lowercase , layer_norm_epsilon=_lowercase ) )
def UpperCAmelCase__ ( self , _lowercase , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=None , ) -> List[Any]:
'''simple docstring'''
snake_case_ : Tuple = self.layer[0](
_lowercase , conditioning_emb=_lowercase , attention_mask=_lowercase , )
if encoder_hidden_states is not None:
snake_case_ : Tuple = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to(
encoder_hidden_states.dtype )
snake_case_ : str = self.layer[1](
_lowercase , key_value_states=_lowercase , attention_mask=_lowercase , )
# Apply Film Conditional Feed Forward layer
snake_case_ : Any = self.layer[-1](_lowercase , _lowercase )
return (hidden_states,)
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase , _lowercase , _lowercase ) -> str:
'''simple docstring'''
super().__init__()
snake_case_ : Any = TaLayerNorm(_lowercase )
snake_case_ : List[Any] = TaFiLMLayer(in_features=d_model * 4 , out_features=_lowercase )
snake_case_ : Union[str, Any] = Attention(query_dim=_lowercase , heads=_lowercase , dim_head=_lowercase , out_bias=_lowercase , scale_qk=_lowercase )
snake_case_ : List[Any] = nn.Dropout(_lowercase )
def UpperCAmelCase__ ( self , _lowercase , _lowercase=None , _lowercase=None , ) -> Optional[Any]:
'''simple docstring'''
snake_case_ : Dict = self.layer_norm(_lowercase )
if conditioning_emb is not None:
snake_case_ : str = self.FiLMLayer(_lowercase , _lowercase )
# Self-attention block
snake_case_ : List[Any] = self.attention(_lowercase )
snake_case_ : List[str] = hidden_states + self.dropout(_lowercase )
return hidden_states
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) -> List[Any]:
'''simple docstring'''
super().__init__()
snake_case_ : List[Any] = Attention(query_dim=_lowercase , heads=_lowercase , dim_head=_lowercase , out_bias=_lowercase , scale_qk=_lowercase )
snake_case_ : Union[str, Any] = TaLayerNorm(_lowercase , eps=_lowercase )
snake_case_ : Optional[Any] = nn.Dropout(_lowercase )
def UpperCAmelCase__ ( self , _lowercase , _lowercase=None , _lowercase=None , ) -> Optional[int]:
'''simple docstring'''
snake_case_ : List[Any] = self.layer_norm(_lowercase )
snake_case_ : Optional[Any] = self.attention(
_lowercase , encoder_hidden_states=_lowercase , attention_mask=attention_mask.squeeze(1 ) , )
snake_case_ : Any = hidden_states + self.dropout(_lowercase )
return layer_output
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase , _lowercase , _lowercase ) -> Dict:
'''simple docstring'''
super().__init__()
snake_case_ : Tuple = TaDenseGatedActDense(d_model=_lowercase , d_ff=_lowercase , dropout_rate=_lowercase )
snake_case_ : List[Any] = TaFiLMLayer(in_features=d_model * 4 , out_features=_lowercase )
snake_case_ : Optional[int] = TaLayerNorm(_lowercase , eps=_lowercase )
snake_case_ : Tuple = nn.Dropout(_lowercase )
def UpperCAmelCase__ ( self , _lowercase , _lowercase=None ) -> str:
'''simple docstring'''
snake_case_ : List[Any] = self.layer_norm(_lowercase )
if conditioning_emb is not None:
snake_case_ : Optional[int] = self.film(_lowercase , _lowercase )
snake_case_ : int = self.DenseReluDense(_lowercase )
snake_case_ : Optional[Any] = hidden_states + self.dropout(_lowercase )
return hidden_states
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase , _lowercase ) -> Optional[int]:
'''simple docstring'''
super().__init__()
snake_case_ : Optional[int] = nn.Linear(_lowercase , _lowercase , bias=_lowercase )
snake_case_ : Optional[int] = nn.Linear(_lowercase , _lowercase , bias=_lowercase )
snake_case_ : Any = nn.Linear(_lowercase , _lowercase , bias=_lowercase )
snake_case_ : int = nn.Dropout(_lowercase )
snake_case_ : Optional[int] = NewGELUActivation()
def UpperCAmelCase__ ( self , _lowercase ) -> int:
'''simple docstring'''
snake_case_ : str = self.act(self.wi_a(_lowercase ) )
snake_case_ : Dict = self.wi_a(_lowercase )
snake_case_ : Any = hidden_gelu * hidden_linear
snake_case_ : List[Any] = self.dropout(_lowercase )
snake_case_ : Tuple = self.wo(_lowercase )
return hidden_states
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase=1E-6 ) -> str:
'''simple docstring'''
super().__init__()
snake_case_ : Union[str, Any] = nn.Parameter(torch.ones(_lowercase ) )
snake_case_ : int = eps
def UpperCAmelCase__ ( self , _lowercase ) -> List[Any]:
'''simple docstring'''
snake_case_ : Tuple = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=_lowercase )
snake_case_ : Any = hidden_states * torch.rsqrt(variance + self.variance_epsilon )
# convert into half-precision if necessary
if self.weight.dtype in [torch.floataa, torch.bfloataa]:
snake_case_ : str = hidden_states.to(self.weight.dtype )
return self.weight * hidden_states
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def UpperCAmelCase__ ( self , _lowercase ) -> torch.Tensor:
'''simple docstring'''
return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(_lowercase , 3.0 )) ))
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self , _lowercase , _lowercase ) -> Any:
'''simple docstring'''
super().__init__()
snake_case_ : List[Any] = nn.Linear(_lowercase , out_features * 2 , bias=_lowercase )
def UpperCAmelCase__ ( self , _lowercase , _lowercase ) -> List[Any]:
'''simple docstring'''
snake_case_ : List[Any] = self.scale_bias(_lowercase )
snake_case_ , snake_case_ : Any = torch.chunk(_lowercase , 2 , -1 )
snake_case_ : Optional[Any] = x * (1 + scale) + shift
return x
| 58 | 0 |
'''simple docstring'''
import math
def lowerCAmelCase_ ( __A : int ):
'''simple docstring'''
if not isinstance(__A , __A ):
snake_case: List[str] = f"""Input value of [number={number}] must be an integer"""
raise TypeError(__A )
if number < 1:
snake_case: int = f"""Input value of [number={number}] must be > 0"""
raise ValueError(__A )
elif number == 1:
return 3
elif number == 2:
return 5
else:
snake_case: int = int(math.log(number // 3 , 2 ) ) + 2
snake_case: str = [3, 5]
snake_case: List[str] = 2
snake_case: List[Any] = 3
for block in range(1 , __A ):
for _ in range(__A ):
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] )
proth_index += 1
increment *= 2
return proth_list[number - 1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for number in range(11):
__UpperCAmelCase = 0
try:
__UpperCAmelCase = proth(number)
except ValueError:
print(F'ValueError: there is no {number}th Proth number')
continue
print(F'The {number}th Proth number: {value}') | 692 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {
"microsoft/swinv2-tiny-patch4-window8-256": (
"https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json"
),
}
class SCREAMING_SNAKE_CASE ( snake_case ):
'''simple docstring'''
__UpperCamelCase = "swinv2"
__UpperCamelCase = {
"num_attention_heads": "num_heads",
"num_hidden_layers": "num_layers",
}
def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=96 , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[3, 6, 12, 24] , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=32 , **SCREAMING_SNAKE_CASE__ , ):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE__ )
snake_case: int = image_size
snake_case: Union[str, Any] = patch_size
snake_case: List[str] = num_channels
snake_case: Tuple = embed_dim
snake_case: str = depths
snake_case: Any = len(SCREAMING_SNAKE_CASE__ )
snake_case: Optional[int] = num_heads
snake_case: Optional[int] = window_size
snake_case: Any = mlp_ratio
snake_case: Optional[int] = qkv_bias
snake_case: Union[str, Any] = hidden_dropout_prob
snake_case: List[str] = attention_probs_dropout_prob
snake_case: Dict = drop_path_rate
snake_case: List[str] = hidden_act
snake_case: int = use_absolute_embeddings
snake_case: Any = layer_norm_eps
snake_case: Dict = initializer_range
snake_case: List[Any] = encoder_stride
# we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
snake_case: Tuple = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE__ ) - 1) )
snake_case: Union[str, Any] = (0, 0, 0, 0) | 692 | 1 |
def __a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]:
'''simple docstring'''
if index == r:
for j in range(_SCREAMING_SNAKE_CASE ):
print(data[j] , end=''' ''' )
print(''' ''' )
return
# When no more elements are there to put in data[]
if i >= n:
return
# current is included, put next at next location
__UpperCAmelCase = arr[i]
combination_util(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 , _SCREAMING_SNAKE_CASE , i + 1 )
# current is excluded, replace it with
# next (Note that i+1 is passed, but
# index is not changed)
combination_util(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , i + 1 )
# The main function that prints all combinations
# of size r in arr[] of size n. This function
# mainly uses combinationUtil()
def __a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any:
'''simple docstring'''
__UpperCAmelCase = [0] * r
# Print all combination using temporary array 'data[]'
combination_util(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , _SCREAMING_SNAKE_CASE , 0 )
if __name__ == "__main__":
# Driver code to check the function above
A_ : List[str] = [10, 20, 30, 40, 50]
print_combination(arr, len(arr), 3)
# This code is contributed by Ambuj sahu
| 303 |
'''simple docstring'''
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
from seqaseq_trainer import SeqaSeqTrainer
from seqaseq_training_args import SeqaSeqTrainingArguments
import transformers
from transformers import (
AutoConfig,
AutoModelForSeqaSeqLM,
AutoTokenizer,
HfArgumentParser,
MBartTokenizer,
MBartTokenizerFast,
set_seed,
)
from transformers.trainer_utils import EvaluationStrategy, is_main_process
from transformers.training_args import ParallelMode
from utils import (
SeqaSeqDataCollator,
SeqaSeqDataset,
assert_all_frozen,
build_compute_metrics_fn,
check_output_dir,
freeze_embeds,
freeze_params,
lmap,
save_json,
use_task_specific_params,
write_txt_file,
)
_lowerCamelCase = logging.getLogger(__name__)
@dataclass
class _snake_case :
__A : str =field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"})
__A : Optional[str] =field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "Pretrained config name or path if not the same as model_name"})
__A : Optional[str] =field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"})
__A : Optional[str] =field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , )
__A : bool =field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether tp freeze the encoder."})
__A : bool =field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to freeze the embeddings."})
@dataclass
class _snake_case :
__A : str =field(
metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."})
__A : Optional[str] =field(
default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , )
__A : Optional[int] =field(
default=10_24 , metadata={
"help": (
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
} , )
__A : Optional[int] =field(
default=1_28 , metadata={
"help": (
"The maximum total sequence length for target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
} , )
__A : Optional[int] =field(
default=1_42 , metadata={
"help": (
"The maximum total sequence length for validation target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded. "
"This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
"during ``evaluate`` and ``predict``."
)
} , )
__A : Optional[int] =field(
default=1_42 , metadata={
"help": (
"The maximum total sequence length for test target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
} , )
__A : Optional[int] =field(default=-1 , metadata={"help": "# training examples. -1 means use all."})
__A : Optional[int] =field(default=-1 , metadata={"help": "# validation examples. -1 means use all."})
__A : Optional[int] =field(default=-1 , metadata={"help": "# test examples. -1 means use all."})
__A : Optional[str] =field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Source language id for translation."})
__A : Optional[str] =field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Target language id for translation."})
__A : Optional[int] =field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "# num_beams to use for evaluation."})
__A : bool =field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , )
def a__ ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str ) -> Union[str, Any]:
"""simple docstring"""
logger.info(F'''***** {split} metrics *****''' )
for key in sorted(metrics.keys() ):
logger.info(F''' {key} = {metrics[key]}''' )
save_json(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , F'''{split}_results.json''' ) )
def a__ ( ) -> Any:
"""simple docstring"""
UpperCAmelCase_ : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = parser.parse_args_into_dataclasses()
check_output_dir(_SCREAMING_SNAKE_CASE )
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , )
logger.warning(
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
logger.info("Training/evaluation parameters %s" , _SCREAMING_SNAKE_CASE )
# Set seed
set_seed(training_args.seed )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
UpperCAmelCase_ : List[str] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
UpperCAmelCase_ : List[Any] = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout")
for p in extra_model_params:
if getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
assert hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute'''
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
UpperCAmelCase_ : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(
model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , )
# use task specific params
use_task_specific_params(_SCREAMING_SNAKE_CASE , data_args.task )
# set num_beams for evaluation
if data_args.eval_beams is None:
UpperCAmelCase_ : Dict = model.config.num_beams
# set decoder_start_token_id for MBart
if model.config.decoder_start_token_id is None and isinstance(_SCREAMING_SNAKE_CASE , (MBartTokenizer, MBartTokenizerFast) ):
assert (
data_args.tgt_lang is not None and data_args.src_lang is not None
), "mBart requires --tgt_lang and --src_lang"
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
UpperCAmelCase_ : Dict = tokenizer.lang_code_to_id[data_args.tgt_lang]
else:
UpperCAmelCase_ : List[Any] = tokenizer.convert_tokens_to_ids(data_args.tgt_lang )
if model_args.freeze_embeds:
freeze_embeds(_SCREAMING_SNAKE_CASE )
if model_args.freeze_encoder:
freeze_params(model.get_encoder() )
assert_all_frozen(model.get_encoder() )
UpperCAmelCase_ : Dict = SeqaSeqDataset
# Get datasets
UpperCAmelCase_ : Tuple = (
dataset_class(
_SCREAMING_SNAKE_CASE , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , )
if training_args.do_train
else None
)
UpperCAmelCase_ : Dict = (
dataset_class(
_SCREAMING_SNAKE_CASE , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , )
if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO
else None
)
UpperCAmelCase_ : int = (
dataset_class(
_SCREAMING_SNAKE_CASE , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , )
if training_args.do_predict
else None
)
# Initialize our Trainer
UpperCAmelCase_ : Optional[Any] = (
build_compute_metrics_fn(data_args.task , _SCREAMING_SNAKE_CASE ) if training_args.predict_with_generate else None
)
UpperCAmelCase_ : List[str] = SeqaSeqTrainer(
model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , data_args=_SCREAMING_SNAKE_CASE , train_dataset=_SCREAMING_SNAKE_CASE , eval_dataset=_SCREAMING_SNAKE_CASE , data_collator=SeqaSeqDataCollator(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , )
UpperCAmelCase_ : List[Any] = {}
# Training
if training_args.do_train:
logger.info("*** Train ***" )
UpperCAmelCase_ : Any = trainer.train(
model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None )
UpperCAmelCase_ : int = train_result.metrics
UpperCAmelCase_ : Dict = data_args.n_train
trainer.save_model() # this also saves the tokenizer
if trainer.is_world_process_zero():
handle_metrics("train" , _SCREAMING_SNAKE_CASE , training_args.output_dir )
all_metrics.update(_SCREAMING_SNAKE_CASE )
# Need to save the state, since Trainer.save_model saves only the tokenizer with the model
trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) )
# For convenience, we also re-save the tokenizer to the same directory,
# so that you can share your model easily on huggingface.co/models =)
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***" )
UpperCAmelCase_ : Union[str, Any] = trainer.evaluate(metric_key_prefix="val" )
UpperCAmelCase_ : Optional[Any] = data_args.n_val
UpperCAmelCase_ : Union[str, Any] = round(metrics["val_loss"] , 4 )
if trainer.is_world_process_zero():
handle_metrics("val" , _SCREAMING_SNAKE_CASE , training_args.output_dir )
all_metrics.update(_SCREAMING_SNAKE_CASE )
if training_args.do_predict:
logger.info("*** Predict ***" )
UpperCAmelCase_ : List[Any] = trainer.predict(test_dataset=_SCREAMING_SNAKE_CASE , metric_key_prefix="test" )
UpperCAmelCase_ : List[str] = test_output.metrics
UpperCAmelCase_ : int = data_args.n_test
if trainer.is_world_process_zero():
UpperCAmelCase_ : Optional[Any] = round(metrics["test_loss"] , 4 )
handle_metrics("test" , _SCREAMING_SNAKE_CASE , training_args.output_dir )
all_metrics.update(_SCREAMING_SNAKE_CASE )
if training_args.predict_with_generate:
UpperCAmelCase_ : Optional[int] = tokenizer.batch_decode(
test_output.predictions , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[int] = lmap(str.strip , _SCREAMING_SNAKE_CASE )
write_txt_file(_SCREAMING_SNAKE_CASE , os.path.join(training_args.output_dir , "test_generations.txt" ) )
if trainer.is_world_process_zero():
save_json(_SCREAMING_SNAKE_CASE , os.path.join(training_args.output_dir , "all_results.json" ) )
return all_metrics
def a__ ( _SCREAMING_SNAKE_CASE : str ) -> Optional[int]:
"""simple docstring"""
main()
if __name__ == "__main__":
main()
| 71 | 0 |
import os
from datetime import datetime as dt
from github import Github
a : int = [
'''good first issue''',
'''good second issue''',
'''good difficult issue''',
'''enhancement''',
'''new pipeline/model''',
'''new scheduler''',
'''wip''',
]
def lowercase_ ( ):
'''simple docstring'''
__lowercase = Github(os.environ['''GITHUB_TOKEN'''] )
__lowercase = g.get_repo('''huggingface/diffusers''' )
__lowercase = repo.get_issues(state='''open''' )
for issue in open_issues:
__lowercase = sorted(issue.get_comments() , key=lambda _UpperCamelCase : i.created_at , reverse=_UpperCamelCase )
__lowercase = comments[0] if len(_UpperCamelCase ) > 0 else None
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and (dt.utcnow() - issue.updated_at).days > 7
and (dt.utcnow() - issue.created_at).days >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Closes the issue after 7 days of inactivity since the Stalebot notification.
issue.edit(state='''closed''' )
elif (
"stale" in issue.get_labels()
and last_comment is not None
and last_comment.user.login != "github-actions[bot]"
):
# Opens the issue if someone other than Stalebot commented.
issue.edit(state='''open''' )
issue.remove_from_labels('''stale''' )
elif (
(dt.utcnow() - issue.updated_at).days > 23
and (dt.utcnow() - issue.created_at).days >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Post a Stalebot notification after 23 days of inactivity.
issue.create_comment(
'''This issue has been automatically marked as stale because it has not had '''
'''recent activity. If you think this still needs to be addressed '''
'''please comment on this thread.\n\nPlease note that issues that do not follow the '''
'''[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) '''
'''are likely to be ignored.''' )
issue.add_to_labels('''stale''' )
if __name__ == "__main__":
main()
| 704 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : List[str] = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Union[str, Any] = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
a : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 527 | 0 |
import time
from contextlib import contextmanager
from pathlib import Path
import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder
a_ = '__DUMMY_TRANSFORMERS_USER__'
a_ = 'Dummy User'
a_ = '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'
a_ = 'https://hub-ci.huggingface.co'
a_ = CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}'
a_ = CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}'
a_ = Path('~/.huggingface/hub_ci_token').expanduser()
@pytest.fixture
def __lowercase ( lowerCamelCase : List[Any] ):
monkeypatch.setattr(
'huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE' , lowerCamelCase )
@pytest.fixture
def __lowercase ( lowerCamelCase : List[str] ):
monkeypatch.setattr('datasets.config.HF_ENDPOINT' , lowerCamelCase )
monkeypatch.setattr('datasets.config.HUB_DATASETS_URL' , lowerCamelCase )
@pytest.fixture
def __lowercase ( lowerCamelCase : Dict ):
monkeypatch.setattr('huggingface_hub.hf_api.HfFolder.path_token' , lowerCamelCase )
@pytest.fixture
def __lowercase ( lowerCamelCase : List[Any] , lowerCamelCase : int ):
HfFolder.save_token(lowerCamelCase )
yield
HfFolder.delete_token()
@pytest.fixture(scope='session' )
def __lowercase ( ):
return HfApi(endpoint=lowerCamelCase )
@pytest.fixture(scope='session' )
def __lowercase ( lowerCamelCase : HfApi ):
UpperCamelCase_ : Tuple = HfFolder.get_token()
HfFolder.save_token(lowerCamelCase )
yield CI_HUB_USER_TOKEN
if previous_token is not None:
HfFolder.save_token(lowerCamelCase )
@pytest.fixture
def __lowercase ( lowerCamelCase : List[str] ):
def _cleanup_repo(lowerCamelCase : Tuple ):
hf_api.delete_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' )
return _cleanup_repo
@pytest.fixture
def __lowercase ( lowerCamelCase : int ):
@contextmanager
def _temporary_repo(lowerCamelCase : Optional[int] ):
try:
yield repo_id
finally:
cleanup_repo(lowerCamelCase )
return _temporary_repo
@pytest.fixture(scope='session' )
def __lowercase ( lowerCamelCase : HfApi , lowerCamelCase : Optional[int] , lowerCamelCase : str ):
UpperCamelCase_ : Dict = F"repo_txt_data-{int(time.time() * 10e3 )}"
UpperCamelCase_ : Tuple = F"{CI_HUB_USER}/{repo_name}"
hf_api.create_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' , private=lowerCamelCase )
hf_api.upload_file(
token=lowerCamelCase , path_or_fileobj=str(lowerCamelCase ) , path_in_repo='data/text_data.txt' , repo_id=lowerCamelCase , repo_type='dataset' , )
yield repo_id
try:
hf_api.delete_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def __lowercase ( lowerCamelCase : int , lowerCamelCase : Optional[int] , lowerCamelCase : List[str] ):
return hf_private_dataset_repo_txt_data_
@pytest.fixture(scope='session' )
def __lowercase ( lowerCamelCase : HfApi , lowerCamelCase : Optional[Any] , lowerCamelCase : Union[str, Any] ):
UpperCamelCase_ : List[Any] = F"repo_zipped_txt_data-{int(time.time() * 10e3 )}"
UpperCamelCase_ : Union[str, Any] = F"{CI_HUB_USER}/{repo_name}"
hf_api.create_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' , private=lowerCamelCase )
hf_api.upload_file(
token=lowerCamelCase , path_or_fileobj=str(lowerCamelCase ) , path_in_repo='data.zip' , repo_id=lowerCamelCase , repo_type='dataset' , )
yield repo_id
try:
hf_api.delete_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def __lowercase ( lowerCamelCase : List[Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : List[str] ):
return hf_private_dataset_repo_zipped_txt_data_
@pytest.fixture(scope='session' )
def __lowercase ( lowerCamelCase : HfApi , lowerCamelCase : Any , lowerCamelCase : str ):
UpperCamelCase_ : List[Any] = F"repo_zipped_img_data-{int(time.time() * 10e3 )}"
UpperCamelCase_ : Optional[Any] = F"{CI_HUB_USER}/{repo_name}"
hf_api.create_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' , private=lowerCamelCase )
hf_api.upload_file(
token=lowerCamelCase , path_or_fileobj=str(lowerCamelCase ) , path_in_repo='data.zip' , repo_id=lowerCamelCase , repo_type='dataset' , )
yield repo_id
try:
hf_api.delete_repo(lowerCamelCase , token=lowerCamelCase , repo_type='dataset' )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : str , lowerCamelCase : str ):
return hf_private_dataset_repo_zipped_img_data_
| 417 | import unittest
import numpy as np
import torch
from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class _lowercase ( unittest.TestCase ):
@property
def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[Any]:
"""simple docstring"""
torch.manual_seed(0 )
UpperCamelCase_ : Optional[Any] = UNetaDModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , )
return model
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase_ : Tuple = self.dummy_uncond_unet
UpperCamelCase_ : List[Any] = ScoreSdeVeScheduler()
UpperCamelCase_ : int = ScoreSdeVePipeline(unet=snake_case , scheduler=snake_case )
sde_ve.to(snake_case )
sde_ve.set_progress_bar_config(disable=snake_case )
UpperCamelCase_ : Union[str, Any] = torch.manual_seed(0 )
UpperCamelCase_ : int = sde_ve(num_inference_steps=2 , output_type='numpy' , generator=snake_case ).images
UpperCamelCase_ : List[Any] = torch.manual_seed(0 )
UpperCamelCase_ : Optional[Any] = sde_ve(num_inference_steps=2 , output_type='numpy' , generator=snake_case , return_dict=snake_case )[
0
]
UpperCamelCase_ : Union[str, Any] = image[0, -3:, -3:, -1]
UpperCamelCase_ : Optional[int] = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
UpperCamelCase_ : Tuple = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch
class _lowercase ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase_ : Dict = 'google/ncsnpp-church-256'
UpperCamelCase_ : Dict = UNetaDModel.from_pretrained(snake_case )
UpperCamelCase_ : List[Any] = ScoreSdeVeScheduler.from_pretrained(snake_case )
UpperCamelCase_ : Any = ScoreSdeVePipeline(unet=snake_case , scheduler=snake_case )
sde_ve.to(snake_case )
sde_ve.set_progress_bar_config(disable=snake_case )
UpperCamelCase_ : Optional[int] = torch.manual_seed(0 )
UpperCamelCase_ : Any = sde_ve(num_inference_steps=1_0 , output_type='numpy' , generator=snake_case ).images
UpperCamelCase_ : Dict = image[0, -3:, -3:, -1]
assert image.shape == (1, 2_5_6, 2_5_6, 3)
UpperCamelCase_ : List[Any] = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 417 | 1 |
'''simple docstring'''
import warnings
from contextlib import contextmanager
from ....processing_utils import ProcessorMixin
class UpperCAmelCase ( lowercase_):
"""simple docstring"""
lowerCAmelCase_ = """MCTCTFeatureExtractor"""
lowerCAmelCase_ = """AutoTokenizer"""
def __init__( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] ) -> Optional[int]:
super().__init__(UpperCamelCase__ , UpperCamelCase__ )
_UpperCamelCase =self.feature_extractor
_UpperCamelCase =False
def __call__( self : Tuple , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : Optional[int] ) -> str:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*UpperCamelCase__ , **UpperCamelCase__ )
if "raw_speech" in kwargs:
warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' )
_UpperCamelCase =kwargs.pop('''raw_speech''' )
else:
_UpperCamelCase =kwargs.pop('''audio''' , UpperCamelCase__ )
_UpperCamelCase =kwargs.pop('''sampling_rate''' , UpperCamelCase__ )
_UpperCamelCase =kwargs.pop('''text''' , UpperCamelCase__ )
if len(UpperCamelCase__ ) > 0:
_UpperCamelCase =args[0]
_UpperCamelCase =args[1:]
if audio is None and text is None:
raise ValueError('''You need to specify either an `audio` or `text` input to process.''' )
if audio is not None:
_UpperCamelCase =self.feature_extractor(UpperCamelCase__ , *UpperCamelCase__ , sampling_rate=UpperCamelCase__ , **UpperCamelCase__ )
if text is not None:
_UpperCamelCase =self.tokenizer(UpperCamelCase__ , **UpperCamelCase__ )
if text is None:
return inputs
elif audio is None:
return encodings
else:
_UpperCamelCase =encodings['''input_ids''']
return inputs
def UpperCamelCase__ ( self : int , *UpperCamelCase__ : int , **UpperCamelCase__ : List[str] ) -> int:
return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ )
def UpperCamelCase__ ( self : Dict , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : int ) -> Tuple:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor.pad(*UpperCamelCase__ , **UpperCamelCase__ )
_UpperCamelCase =kwargs.pop('''input_features''' , UpperCamelCase__ )
_UpperCamelCase =kwargs.pop('''labels''' , UpperCamelCase__ )
if len(UpperCamelCase__ ) > 0:
_UpperCamelCase =args[0]
_UpperCamelCase =args[1:]
if input_features is not None:
_UpperCamelCase =self.feature_extractor.pad(UpperCamelCase__ , *UpperCamelCase__ , **UpperCamelCase__ )
if labels is not None:
_UpperCamelCase =self.tokenizer.pad(UpperCamelCase__ , **UpperCamelCase__ )
if labels is None:
return input_features
elif input_features is None:
return labels
else:
_UpperCamelCase =labels['''input_ids''']
return input_features
def UpperCamelCase__ ( self : Optional[Any] , *UpperCamelCase__ : Dict , **UpperCamelCase__ : int ) -> List[Any]:
return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ )
@contextmanager
def UpperCamelCase__ ( self : List[Any] ) -> Tuple:
warnings.warn(
'''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
'''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
'''your audio inputs, or in a separate call.''' )
_UpperCamelCase =True
_UpperCamelCase =self.tokenizer
yield
_UpperCamelCase =self.feature_extractor
_UpperCamelCase =False
| 704 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__lowerCamelCase : Optional[int] = {
'configuration_xmod': [
'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP',
'XmodConfig',
'XmodOnnxConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : int = [
'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST',
'XmodForCausalLM',
'XmodForMaskedLM',
'XmodForMultipleChoice',
'XmodForQuestionAnswering',
'XmodForSequenceClassification',
'XmodForTokenClassification',
'XmodModel',
'XmodPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xmod import (
XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
XmodForCausalLM,
XmodForMaskedLM,
XmodForMultipleChoice,
XmodForQuestionAnswering,
XmodForSequenceClassification,
XmodForTokenClassification,
XmodModel,
XmodPreTrainedModel,
)
else:
import sys
__lowerCamelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 271 | 0 |
'''simple docstring'''
from math import loga
def UpperCamelCase__ ( __magic_name__ : int ) -> int:
'''simple docstring'''
if a < 0:
raise ValueError("""Input value must be a positive integer""" )
elif isinstance(__magic_name__ , __magic_name__ ):
raise TypeError("""Input value must be a 'int' type""" )
return 0 if (a == 0) else int(loga(a & -a ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 38 | from .integrations import (
is_optuna_available,
is_ray_available,
is_sigopt_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
run_hp_search_sigopt,
run_hp_search_wandb,
)
from .trainer_utils import (
HPSearchBackend,
default_hp_space_optuna,
default_hp_space_ray,
default_hp_space_sigopt,
default_hp_space_wandb,
)
from .utils import logging
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
class a :
"""simple docstring"""
lowerCamelCase :str
lowerCamelCase :str = None
@staticmethod
def UpperCAmelCase ( ) -> List[str]:
raise NotImplementedError
def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) -> Dict:
raise NotImplementedError
def UpperCAmelCase ( self , lowerCAmelCase_ ) -> Tuple:
raise NotImplementedError
def UpperCAmelCase ( self ) -> List[str]:
if not self.is_available():
raise RuntimeError(
F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' )
@classmethod
def UpperCAmelCase ( cls ) -> List[str]:
return F'''`pip install {cls.pip_package or cls.name}`'''
class a ( __lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase :Any = '''optuna'''
@staticmethod
def UpperCAmelCase ( ) -> Tuple:
return is_optuna_available()
def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) -> Optional[Any]:
return run_hp_search_optuna(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ )
def UpperCAmelCase ( self , lowerCAmelCase_ ) -> str:
return default_hp_space_optuna(lowerCAmelCase_ )
class a ( __lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase :Tuple = '''ray'''
lowerCamelCase :int = '''\'ray[tune]\''''
@staticmethod
def UpperCAmelCase ( ) -> Dict:
return is_ray_available()
def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) -> int:
return run_hp_search_ray(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ )
def UpperCAmelCase ( self , lowerCAmelCase_ ) -> Optional[int]:
return default_hp_space_ray(lowerCAmelCase_ )
class a ( __lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase :Any = '''sigopt'''
@staticmethod
def UpperCAmelCase ( ) -> Optional[int]:
return is_sigopt_available()
def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) -> Union[str, Any]:
return run_hp_search_sigopt(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ )
def UpperCAmelCase ( self , lowerCAmelCase_ ) -> Union[str, Any]:
return default_hp_space_sigopt(lowerCAmelCase_ )
class a ( __lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase :Any = '''wandb'''
@staticmethod
def UpperCAmelCase ( ) -> int:
return is_wandb_available()
def UpperCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) -> List[Any]:
return run_hp_search_wandb(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ )
def UpperCAmelCase ( self , lowerCAmelCase_ ) -> Tuple:
return default_hp_space_wandb(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE = {
HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}
def snake_case ( ) -> str:
_A = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
if len(snake_case__) > 0:
_A = available_backends[0].name
if len(snake_case__) > 1:
logger.info(
F'''{len(snake_case__)} hyperparameter search backends available. Using {name} as the default.''')
return name
raise RuntimeError(
"""No hyperparameter search backend available.\n"""
+ """\n""".join(
F''' - To install {backend.name} run {backend.pip_install()}'''
for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()))
| 401 | 0 |
import numpy as np
import torch
from torch.utils.data import Dataset
from utils import logger
class UpperCAmelCase__ ( __snake_case ):
def __init__( self ,A__ ,A__ ):
_A : str = params
_A : Tuple = np.array(A__ )
_A : Dict = np.array([len(A__ ) for t in data] )
self.check()
self.remove_long_sequences()
self.remove_empty_sequences()
self.remove_unknown_sequences()
self.check()
self.print_statistics()
def __getitem__( self ,A__ ):
return (self.token_ids[index], self.lengths[index])
def __len__( self ):
return len(self.lengths )
def A__ ( self ):
assert len(self.token_ids ) == len(self.lengths )
assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) )
def A__ ( self ):
_A : List[str] = self.params.max_model_input_size
_A : List[Any] = self.lengths > max_len
logger.info(f"""Splitting {sum(A__ )} too long sequences.""" )
def divide_chunks(A__ ,A__ ):
return [l[i : i + n] for i in range(0 ,len(A__ ) ,A__ )]
_A : Dict = []
_A : Optional[Any] = []
if self.params.mlm:
_A : Optional[int] = self.params.special_tok_ids['''cls_token'''], self.params.special_tok_ids['''sep_token''']
else:
_A : str = self.params.special_tok_ids['''bos_token'''], self.params.special_tok_ids['''eos_token''']
for seq_, len_ in zip(self.token_ids ,self.lengths ):
assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
if len_ <= max_len:
new_tok_ids.append(seq_ )
new_lengths.append(len_ )
else:
_A : str = []
for sub_s in divide_chunks(seq_ ,max_len - 2 ):
if sub_s[0] != cls_id:
_A : Optional[int] = np.insert(A__ ,0 ,A__ )
if sub_s[-1] != sep_id:
_A : List[Any] = np.insert(A__ ,len(A__ ) ,A__ )
assert len(A__ ) <= max_len
assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
sub_seqs.append(A__ )
new_tok_ids.extend(A__ )
new_lengths.extend([len(A__ ) for l in sub_seqs] )
_A : Union[str, Any] = np.array(A__ )
_A : List[str] = np.array(A__ )
def A__ ( self ):
_A : str = len(self )
_A : str = self.lengths > 11
_A : str = self.token_ids[indices]
_A : Dict = self.lengths[indices]
_A : Optional[int] = len(self )
logger.info(f"""Remove {init_size - new_size} too short (<=11 tokens) sequences.""" )
def A__ ( self ):
if "unk_token" not in self.params.special_tok_ids:
return
else:
_A : Any = self.params.special_tok_ids['''unk_token''']
_A : Dict = len(self )
_A : str = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] )
_A : Union[str, Any] = (unk_occs / self.lengths) < 0.5
_A : Dict = self.token_ids[indices]
_A : List[Any] = self.lengths[indices]
_A : List[Any] = len(self )
logger.info(f"""Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).""" )
def A__ ( self ):
if not self.params.is_master:
return
logger.info(f"""{len(self )} sequences""" )
# data_len = sum(self.lengths)
# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')
# unk_idx = self.params.special_tok_ids['unk_token']
# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')
def A__ ( self ,A__ ):
_A : List[Any] = [t[0] for t in batch]
_A : int = [t[1] for t in batch]
assert len(A__ ) == len(A__ )
# Max for paddings
_A : Optional[int] = max(A__ )
# Pad token ids
if self.params.mlm:
_A : List[Any] = self.params.special_tok_ids['''pad_token''']
else:
_A : Optional[int] = self.params.special_tok_ids['''unk_token''']
_A : Dict = [list(t.astype(A__ ) ) + [pad_idx] * (max_seq_len_ - len(A__ )) for t in token_ids]
assert len(tk_ ) == len(A__ )
assert all(len(A__ ) == max_seq_len_ for t in tk_ )
_A : List[Any] = torch.tensor(tk_ ) # (bs, max_seq_len_)
_A : str = torch.tensor(A__ ) # (bs)
return tk_t, lg_t
| 702 |
from ...configuration_utils import PretrainedConfig
_UpperCamelCase : Tuple ={
'google/tapas-base-finetuned-sqa': (
'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json'
),
'google/tapas-base-finetuned-wtq': (
'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json'
),
'google/tapas-base-finetuned-wikisql-supervised': (
'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json'
),
'google/tapas-base-finetuned-tabfact': (
'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json'
),
}
class UpperCAmelCase__ ( __snake_case ):
__snake_case : List[Any] = "tapas"
def __init__( self ,A__=30522 ,A__=768 ,A__=12 ,A__=12 ,A__=3072 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=1024 ,A__=[3, 256, 256, 2, 256, 256, 10] ,A__=0.02 ,A__=1E-12 ,A__=0 ,A__=10.0 ,A__=0 ,A__=1.0 ,A__=None ,A__=1.0 ,A__=False ,A__=None ,A__=1.0 ,A__=1.0 ,A__=False ,A__=False ,A__="ratio" ,A__=None ,A__=None ,A__=64 ,A__=32 ,A__=False ,A__=True ,A__=False ,A__=False ,A__=True ,A__=False ,A__=None ,A__=None ,**A__ ,):
super().__init__(pad_token_id=A__ ,**A__ )
# BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes)
_A : int = vocab_size
_A : Dict = hidden_size
_A : List[str] = num_hidden_layers
_A : Tuple = num_attention_heads
_A : Any = hidden_act
_A : str = intermediate_size
_A : List[str] = hidden_dropout_prob
_A : List[Any] = attention_probs_dropout_prob
_A : Tuple = max_position_embeddings
_A : Optional[Any] = type_vocab_sizes
_A : List[Any] = initializer_range
_A : Optional[Any] = layer_norm_eps
# Fine-tuning task hyperparameters
_A : Optional[Any] = positive_label_weight
_A : List[Any] = num_aggregation_labels
_A : Union[str, Any] = aggregation_loss_weight
_A : Optional[int] = use_answer_as_supervision
_A : Tuple = answer_loss_importance
_A : Dict = use_normalized_answer_loss
_A : Union[str, Any] = huber_loss_delta
_A : Union[str, Any] = temperature
_A : Optional[Any] = aggregation_temperature
_A : Optional[int] = use_gumbel_for_cells
_A : List[str] = use_gumbel_for_aggregation
_A : int = average_approximation_function
_A : Union[str, Any] = cell_selection_preference
_A : List[str] = answer_loss_cutoff
_A : List[Any] = max_num_rows
_A : List[str] = max_num_columns
_A : Union[str, Any] = average_logits_per_cell
_A : Optional[Any] = select_one_column
_A : List[str] = allow_empty_column_selection
_A : int = init_cell_selection_weights_to_zero
_A : Dict = reset_position_index_per_cell
_A : Dict = disable_per_token_loss
# Aggregation hyperparameters
_A : Tuple = aggregation_labels
_A : Dict = no_aggregation_label_index
if isinstance(self.aggregation_labels ,A__ ):
_A : Dict = {int(A__ ): v for k, v in aggregation_labels.items()}
| 332 | 0 |
"""simple docstring"""
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
__SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE : List[str] = {
'''SenseTime/deformable-detr''': '''https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json''',
# See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}
class lowerCamelCase_( A__ ):
'''simple docstring'''
lowercase__ : Any = 'deformable_detr'
lowercase__ : Tuple = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self , lowerCamelCase__=True , lowerCamelCase__=None , lowerCamelCase__=3 , lowerCamelCase__=3_0_0 , lowerCamelCase__=1_0_2_4 , lowerCamelCase__=6 , lowerCamelCase__=1_0_2_4 , lowerCamelCase__=8 , lowerCamelCase__=6 , lowerCamelCase__=1_0_2_4 , lowerCamelCase__=8 , lowerCamelCase__=0.0 , lowerCamelCase__=True , lowerCamelCase__="relu" , lowerCamelCase__=2_5_6 , lowerCamelCase__=0.1 , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=0.0_2 , lowerCamelCase__=1.0 , lowerCamelCase__=True , lowerCamelCase__=False , lowerCamelCase__="sine" , lowerCamelCase__="resnet50" , lowerCamelCase__=True , lowerCamelCase__=False , lowerCamelCase__=4 , lowerCamelCase__=4 , lowerCamelCase__=4 , lowerCamelCase__=False , lowerCamelCase__=3_0_0 , lowerCamelCase__=False , lowerCamelCase__=1 , lowerCamelCase__=5 , lowerCamelCase__=2 , lowerCamelCase__=1 , lowerCamelCase__=1 , lowerCamelCase__=5 , lowerCamelCase__=2 , lowerCamelCase__=0.1 , lowerCamelCase__=0.2_5 , lowerCamelCase__=False , **lowerCamelCase__ , ):
if backbone_config is not None and use_timm_backbone:
raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' )
if not use_timm_backbone:
if backbone_config is None:
logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' )
_lowerCamelCase = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] )
elif isinstance(lowerCamelCase__ , lowerCamelCase__ ):
_lowerCamelCase = backbone_config.get('''model_type''' )
_lowerCamelCase = CONFIG_MAPPING[backbone_model_type]
_lowerCamelCase = config_class.from_dict(lowerCamelCase__ )
_lowerCamelCase = use_timm_backbone
_lowerCamelCase = backbone_config
_lowerCamelCase = num_channels
_lowerCamelCase = num_queries
_lowerCamelCase = max_position_embeddings
_lowerCamelCase = d_model
_lowerCamelCase = encoder_ffn_dim
_lowerCamelCase = encoder_layers
_lowerCamelCase = encoder_attention_heads
_lowerCamelCase = decoder_ffn_dim
_lowerCamelCase = decoder_layers
_lowerCamelCase = decoder_attention_heads
_lowerCamelCase = dropout
_lowerCamelCase = attention_dropout
_lowerCamelCase = activation_dropout
_lowerCamelCase = activation_function
_lowerCamelCase = init_std
_lowerCamelCase = init_xavier_std
_lowerCamelCase = encoder_layerdrop
_lowerCamelCase = auxiliary_loss
_lowerCamelCase = position_embedding_type
_lowerCamelCase = backbone
_lowerCamelCase = use_pretrained_backbone
_lowerCamelCase = dilation
# deformable attributes
_lowerCamelCase = num_feature_levels
_lowerCamelCase = encoder_n_points
_lowerCamelCase = decoder_n_points
_lowerCamelCase = two_stage
_lowerCamelCase = two_stage_num_proposals
_lowerCamelCase = with_box_refine
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
_lowerCamelCase = class_cost
_lowerCamelCase = bbox_cost
_lowerCamelCase = giou_cost
# Loss coefficients
_lowerCamelCase = mask_loss_coefficient
_lowerCamelCase = dice_loss_coefficient
_lowerCamelCase = bbox_loss_coefficient
_lowerCamelCase = giou_loss_coefficient
_lowerCamelCase = eos_coefficient
_lowerCamelCase = focal_alpha
_lowerCamelCase = disable_custom_kernels
super().__init__(is_encoder_decoder=lowerCamelCase__ , **lowerCamelCase__ )
@property
def snake_case__ ( self ):
return self.encoder_attention_heads
@property
def snake_case__ ( self ):
return self.d_model
def snake_case__ ( self ):
_lowerCamelCase = copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
_lowerCamelCase = self.backbone_config.to_dict()
_lowerCamelCase = self.__class__.model_type
return output
| 661 |
"""simple docstring"""
from __future__ import annotations
from math import ceil, floor, sqrt
def lowerCAmelCase_( lowercase_ : int = 2_00_00_00 ) -> int:
_lowerCamelCase = [0]
_lowerCamelCase = 42
for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ):
triangle_numbers.append(triangle_numbers[-1] + idx )
# we want this to be as close as possible to target
_lowerCamelCase = 0
# the area corresponding to the grid that gives the product closest to target
_lowerCamelCase = 0
# an estimate of b, using the quadratic formula
_lowerCamelCase = 42
# the largest integer less than b_estimate
_lowerCamelCase = 42
# the largest integer less than b_estimate
_lowerCamelCase = 42
# the triangle number corresponding to b_floor
_lowerCamelCase = 42
# the triangle number corresponding to b_ceil
_lowerCamelCase = 42
for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ):
_lowerCamelCase = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2
_lowerCamelCase = floor(lowercase_ )
_lowerCamelCase = ceil(lowercase_ )
_lowerCamelCase = triangle_numbers[b_floor]
_lowerCamelCase = triangle_numbers[b_ceil]
if abs(target - triangle_b_first_guess * triangle_a ) < abs(
target - best_product ):
_lowerCamelCase = triangle_b_first_guess * triangle_a
_lowerCamelCase = idx_a * b_floor
if abs(target - triangle_b_second_guess * triangle_a ) < abs(
target - best_product ):
_lowerCamelCase = triangle_b_second_guess * triangle_a
_lowerCamelCase = idx_a * b_ceil
return area
if __name__ == "__main__":
print(F"""{solution() = }""")
| 661 | 1 |
"""simple docstring"""
from dataclasses import dataclass, field
from typing import Tuple
from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments
if is_tf_available():
import tensorflow as tf
_UpperCamelCase = logging.get_logger(__name__)
@dataclass
class lowerCamelCase__ ( snake_case ):
SCREAMING_SNAKE_CASE = [
'''no_inference''',
'''no_cuda''',
'''no_tpu''',
'''no_speed''',
'''no_memory''',
'''no_env_print''',
'''no_multi_process''',
]
def __init__( self ,**A ):
for deprecated_arg in self.deprecated_args:
if deprecated_arg in kwargs:
UpperCAmelCase = deprecated_arg[3:]
UpperCAmelCase = not kwargs.pop(A )
logger.warning(
F'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or'''
F''' {positive_arg}={kwargs[positive_arg]}''' )
UpperCAmelCase = kwargs.pop("""tpu_name""" ,self.tpu_name )
UpperCAmelCase = kwargs.pop("""device_idx""" ,self.device_idx )
UpperCAmelCase = kwargs.pop("""eager_mode""" ,self.eager_mode )
UpperCAmelCase = kwargs.pop("""use_xla""" ,self.use_xla )
super().__init__(**A )
SCREAMING_SNAKE_CASE = field(
default=snake_case , metadata={'''help''': '''Name of TPU'''} , )
SCREAMING_SNAKE_CASE = field(
default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , )
SCREAMING_SNAKE_CASE = field(default=snake_case , metadata={'''help''': '''Benchmark models in eager model.'''} )
SCREAMING_SNAKE_CASE = field(
default=snake_case , metadata={
'''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
} , )
@cached_property
def _UpperCamelCase ( self ):
requires_backends(self ,["""tf"""] )
UpperCAmelCase = None
if self.tpu:
try:
if self.tpu_name:
UpperCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name )
else:
UpperCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver()
except ValueError:
UpperCAmelCase = None
return tpu
@cached_property
def _UpperCamelCase ( self ):
requires_backends(self ,["""tf"""] )
if self.is_tpu:
tf.config.experimental_connect_to_cluster(self._setup_tpu )
tf.tpu.experimental.initialize_tpu_system(self._setup_tpu )
UpperCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu )
else:
# currently no multi gpu is allowed
if self.is_gpu:
# TODO: Currently only single GPU is supported
tf.config.set_visible_devices(self.gpu_list[self.device_idx] ,"""GPU""" )
UpperCAmelCase = tf.distribute.OneDeviceStrategy(device=F'''/gpu:{self.device_idx}''' )
else:
tf.config.set_visible_devices([] ,"""GPU""" ) # disable GPU
UpperCAmelCase = tf.distribute.OneDeviceStrategy(device=F'''/cpu:{self.device_idx}''' )
return strategy
@property
def _UpperCamelCase ( self ):
requires_backends(self ,["""tf"""] )
return self._setup_tpu is not None
@property
def _UpperCamelCase ( self ):
requires_backends(self ,["""tf"""] )
return self._setup_strategy
@property
def _UpperCamelCase ( self ):
requires_backends(self ,["""tf"""] )
return tf.config.list_physical_devices("""GPU""" )
@property
def _UpperCamelCase ( self ):
requires_backends(self ,["""tf"""] )
if self.cuda:
return len(self.gpu_list )
return 0
@property
def _UpperCamelCase ( self ):
return self.n_gpu > 0
| 74 |
"""simple docstring"""
import argparse
import struct
import unittest
class lowerCamelCase__ :
def __init__( self ,A ):
UpperCAmelCase = data
# Initialize hash values
UpperCAmelCase = [
0x6A_09_E6_67,
0xBB_67_AE_85,
0x3C_6E_F3_72,
0xA5_4F_F5_3A,
0x51_0E_52_7F,
0x9B_05_68_8C,
0x1F_83_D9_AB,
0x5B_E0_CD_19,
]
# Initialize round constants
UpperCAmelCase = [
0x42_8A_2F_98,
0x71_37_44_91,
0xB5_C0_FB_CF,
0xE9_B5_DB_A5,
0x39_56_C2_5B,
0x59_F1_11_F1,
0x92_3F_82_A4,
0xAB_1C_5E_D5,
0xD8_07_AA_98,
0x12_83_5B_01,
0x24_31_85_BE,
0x55_0C_7D_C3,
0x72_BE_5D_74,
0x80_DE_B1_FE,
0x9B_DC_06_A7,
0xC1_9B_F1_74,
0xE4_9B_69_C1,
0xEF_BE_47_86,
0x0F_C1_9D_C6,
0x24_0C_A1_CC,
0x2D_E9_2C_6F,
0x4A_74_84_AA,
0x5C_B0_A9_DC,
0x76_F9_88_DA,
0x98_3E_51_52,
0xA8_31_C6_6D,
0xB0_03_27_C8,
0xBF_59_7F_C7,
0xC6_E0_0B_F3,
0xD5_A7_91_47,
0x06_CA_63_51,
0x14_29_29_67,
0x27_B7_0A_85,
0x2E_1B_21_38,
0x4D_2C_6D_FC,
0x53_38_0D_13,
0x65_0A_73_54,
0x76_6A_0A_BB,
0x81_C2_C9_2E,
0x92_72_2C_85,
0xA2_BF_E8_A1,
0xA8_1A_66_4B,
0xC2_4B_8B_70,
0xC7_6C_51_A3,
0xD1_92_E8_19,
0xD6_99_06_24,
0xF4_0E_35_85,
0x10_6A_A0_70,
0x19_A4_C1_16,
0x1E_37_6C_08,
0x27_48_77_4C,
0x34_B0_BC_B5,
0x39_1C_0C_B3,
0x4E_D8_AA_4A,
0x5B_9C_CA_4F,
0x68_2E_6F_F3,
0x74_8F_82_EE,
0x78_A5_63_6F,
0x84_C8_78_14,
0x8C_C7_02_08,
0x90_BE_FF_FA,
0xA4_50_6C_EB,
0xBE_F9_A3_F7,
0xC6_71_78_F2,
]
UpperCAmelCase = self.preprocessing(self.data )
self.final_hash()
@staticmethod
def _UpperCamelCase ( A ):
UpperCAmelCase = b"""\x80""" + (b"""\x00""" * (63 - (len(A ) + 8) % 64))
UpperCAmelCase = struct.pack(""">Q""" ,(len(A ) * 8) )
return data + padding + big_endian_integer
def _UpperCamelCase ( self ):
# Convert into blocks of 64 bytes
UpperCAmelCase = [
self.preprocessed_data[x : x + 64]
for x in range(0 ,len(self.preprocessed_data ) ,64 )
]
for block in self.blocks:
# Convert the given block into a list of 4 byte integers
UpperCAmelCase = list(struct.unpack(""">16L""" ,A ) )
# add 48 0-ed integers
words += [0] * 48
UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = self.hashes
for index in range(0 ,64 ):
if index > 15:
# modify the zero-ed indexes at the end of the array
UpperCAmelCase = (
self.ror(words[index - 15] ,7 )
^ self.ror(words[index - 15] ,18 )
^ (words[index - 15] >> 3)
)
UpperCAmelCase = (
self.ror(words[index - 2] ,17 )
^ self.ror(words[index - 2] ,19 )
^ (words[index - 2] >> 10)
)
UpperCAmelCase = (
words[index - 16] + sa + words[index - 7] + sa
) % 0x1_00_00_00_00
# Compression
UpperCAmelCase = self.ror(A ,6 ) ^ self.ror(A ,11 ) ^ self.ror(A ,25 )
UpperCAmelCase = (e & f) ^ ((~e & 0xFF_FF_FF_FF) & g)
UpperCAmelCase = (
h + sa + ch + self.round_constants[index] + words[index]
) % 0x1_00_00_00_00
UpperCAmelCase = self.ror(A ,2 ) ^ self.ror(A ,13 ) ^ self.ror(A ,22 )
UpperCAmelCase = (a & b) ^ (a & c) ^ (b & c)
UpperCAmelCase = (sa + maj) % 0x1_00_00_00_00
UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = (
g,
f,
e,
((d + tempa) % 0x1_00_00_00_00),
c,
b,
a,
((tempa + tempa) % 0x1_00_00_00_00),
)
UpperCAmelCase = [a, b, c, d, e, f, g, h]
# Modify final values
UpperCAmelCase = [
((element + mutated_hash_values[index]) % 0x1_00_00_00_00)
for index, element in enumerate(self.hashes )
]
UpperCAmelCase = """""".join([hex(A )[2:].zfill(8 ) for value in self.hashes] )
def _UpperCamelCase ( self ,A ,A ):
return 0xFF_FF_FF_FF & (value << (32 - rotations)) | (value >> rotations)
class lowerCamelCase__ ( unittest.TestCase ):
def _UpperCamelCase ( self ):
import hashlib
UpperCAmelCase = bytes("""Test String""" ,"""utf-8""" )
self.assertEqual(SHAaaa(A ).hash ,hashlib.shaaaa(A ).hexdigest() )
def _a ( ):
"""simple docstring"""
import doctest
doctest.testmod()
UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument(
"""-s""" , """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , )
parser.add_argument(
"""-f""" , """--file""" , dest="""input_file""" , help="""Hash contents of a file""" )
UpperCAmelCase = parser.parse_args()
UpperCAmelCase = args.input_string
# hash input should be a bytestring
if args.input_file:
with open(args.input_file , """rb""" ) as f:
UpperCAmelCase = f.read()
else:
UpperCAmelCase = bytes(_snake_case , """utf-8""" )
print(SHAaaa(_snake_case ).hash )
if __name__ == "__main__":
main()
| 74 | 1 |
import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
import pytest
import transformers
from transformers import (
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
AutoTokenizer,
BertConfig,
BertTokenizer,
BertTokenizerFast,
CTRLTokenizer,
GPTaTokenizer,
GPTaTokenizerFast,
PreTrainedTokenizerFast,
RobertaTokenizer,
RobertaTokenizerFast,
is_tokenizers_available,
)
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.auto.tokenization_auto import (
TOKENIZER_MAPPING,
get_tokenizer_config,
tokenizer_class_from_name,
)
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import (
DUMMY_DIFF_TOKENIZER_IDENTIFIER,
DUMMY_UNKNOWN_IDENTIFIER,
SMALL_MODEL_IDENTIFIER,
RequestCounter,
require_tokenizers,
slow,
)
sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class UpperCAmelCase ( unittest.TestCase ):
def lowerCamelCase_ ( self : Any ):
"""simple docstring"""
UpperCamelCase = 0
@slow
def lowerCamelCase_ ( self : Dict ):
"""simple docstring"""
for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsNotNone(__magic_name__ )
self.assertIsInstance(__magic_name__ , (BertTokenizer, BertTokenizerFast) )
self.assertGreater(len(__magic_name__ ) , 0 )
for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsNotNone(__magic_name__ )
self.assertIsInstance(__magic_name__ , (GPTaTokenizer, GPTaTokenizerFast) )
self.assertGreater(len(__magic_name__ ) , 0 )
def lowerCamelCase_ ( self : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(tokenizer.vocab_size , 1_2 )
def lowerCamelCase_ ( self : List[str] ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , (RobertaTokenizer, RobertaTokenizerFast) )
self.assertEqual(tokenizer.vocab_size , 2_0 )
def lowerCamelCase_ ( self : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = AutoConfig.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , __magic_name__ )
# Check that tokenizer_type ≠ model_type
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , config=__magic_name__ )
self.assertIsInstance(__magic_name__ , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(tokenizer.vocab_size , 1_2 )
def lowerCamelCase_ ( self : str ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(__magic_name__ , """vocab.txt""" ) )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , tokenizer_type="""bert""" , use_fast=__magic_name__ )
self.assertIsInstance(__magic_name__ , __magic_name__ )
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(__magic_name__ , """vocab.json""" ) )
shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(__magic_name__ , """merges.txt""" ) )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , tokenizer_type="""gpt2""" , use_fast=__magic_name__ )
self.assertIsInstance(__magic_name__ , __magic_name__ )
@require_tokenizers
def lowerCamelCase_ ( self : List[Any] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(__magic_name__ , """vocab.txt""" ) )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , tokenizer_type="""bert""" )
self.assertIsInstance(__magic_name__ , __magic_name__ )
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(__magic_name__ , """vocab.json""" ) )
shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(__magic_name__ , """merges.txt""" ) )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , tokenizer_type="""gpt2""" )
self.assertIsInstance(__magic_name__ , __magic_name__ )
def lowerCamelCase_ ( self : Any ):
"""simple docstring"""
with pytest.raises(__magic_name__ ):
AutoTokenizer.from_pretrained("""./""" , tokenizer_type="""xxx""" )
@require_tokenizers
def lowerCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
UpperCamelCase = tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased""" )
self.assertIsInstance(__magic_name__ , (BertTokenizer, BertTokenizerFast) )
if isinstance(__magic_name__ , __magic_name__ ):
self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , __magic_name__ )
else:
self.assertEqual(tokenizer.do_lower_case , __magic_name__ )
self.assertEqual(tokenizer.model_max_length , 5_1_2 )
@require_tokenizers
def lowerCamelCase_ ( self : Dict ):
"""simple docstring"""
for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
with self.assertRaisesRegex(
__magic_name__ , """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" , ):
UpperCamelCase = tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists""" )
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = TOKENIZER_MAPPING.values()
UpperCamelCase = []
for slow_tok, fast_tok in tokenizers:
if slow_tok is not None:
tokenizer_names.append(slow_tok.__name__ )
if fast_tok is not None:
tokenizer_names.append(fast_tok.__name__ )
for tokenizer_name in tokenizer_names:
# must find the right class
tokenizer_class_from_name(__magic_name__ )
@require_tokenizers
def lowerCamelCase_ ( self : Any ):
"""simple docstring"""
self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=__magic_name__ ) , __magic_name__ )
self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ) , __magic_name__ )
@require_tokenizers
def lowerCamelCase_ ( self : str ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained("""distilbert-base-uncased""" , do_lower_case=__magic_name__ )
UpperCamelCase = """Hello, world. How are you?"""
UpperCamelCase = tokenizer.tokenize(__magic_name__ )
self.assertEqual("""[UNK]""" , tokens[0] )
UpperCamelCase = AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" , do_lower_case=__magic_name__ )
UpperCamelCase = tokenizer.tokenize(__magic_name__ )
self.assertEqual("""[UNK]""" , tokens[0] )
@require_tokenizers
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config""" )
self.assertEqual(type(__magic_name__ ) , __magic_name__ )
self.assertEqual(tokenizer.model_max_length , 5_1_2 )
self.assertEqual(tokenizer.vocab_size , 3_0_0_0_0 )
self.assertEqual(tokenizer.unk_token , """[UNK]""" )
self.assertEqual(tokenizer.padding_side , """right""" )
self.assertEqual(tokenizer.truncation_side , """right""" )
def lowerCamelCase_ ( self : List[Any] ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , (BertTokenizer, BertTokenizerFast) )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , tokenizer.__class__ )
self.assertEqual(tokenizera.vocab_size , 1_2 )
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained("""ctrl""" )
# There is no fast CTRL so this always gives us a slow tokenizer.
self.assertIsInstance(__magic_name__ , __magic_name__ )
def lowerCamelCase_ ( self : Optional[int] ):
"""simple docstring"""
UpperCamelCase = get_tokenizer_config("""bert-base-cased""" )
UpperCamelCase = config.pop("""_commit_hash""" , __magic_name__ )
# If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
self.assertEqual(__magic_name__ , {"""do_lower_case""": False} )
# This model does not have a tokenizer_config so we get back an empty dict.
UpperCamelCase = get_tokenizer_config(__magic_name__ )
self.assertDictEqual(__magic_name__ , {} )
# A tokenizer saved with `save_pretrained` always creates a tokenizer config.
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = get_tokenizer_config(__magic_name__ )
# Check the class of the tokenizer was properly saved (note that it always saves the slow class).
self.assertEqual(config["""tokenizer_class"""] , """BertTokenizer""" )
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
try:
AutoConfig.register("""custom""" , __magic_name__ )
AutoTokenizer.register(__magic_name__ , slow_tokenizer_class=__magic_name__ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(__magic_name__ ):
AutoTokenizer.register(__magic_name__ , slow_tokenizer_class=__magic_name__ )
UpperCamelCase = CustomTokenizer.from_pretrained(__magic_name__ )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , __magic_name__ )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
@require_tokenizers
def lowerCamelCase_ ( self : List[Any] ):
"""simple docstring"""
try:
AutoConfig.register("""custom""" , __magic_name__ )
# Can register in two steps
AutoTokenizer.register(__magic_name__ , slow_tokenizer_class=__magic_name__ )
self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) )
AutoTokenizer.register(__magic_name__ , fast_tokenizer_class=__magic_name__ )
self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) )
del TOKENIZER_MAPPING._extra_content[CustomConfig]
# Can register in one step
AutoTokenizer.register(
__magic_name__ , slow_tokenizer_class=__magic_name__ , fast_tokenizer_class=__magic_name__ )
self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(__magic_name__ ):
AutoTokenizer.register(__magic_name__ , fast_tokenizer_class=__magic_name__ )
# We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
# and that model does not have a tokenizer.json
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCamelCase = BertTokenizerFast.from_pretrained(__magic_name__ )
bert_tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = CustomTokenizerFast.from_pretrained(__magic_name__ )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ )
self.assertIsInstance(__magic_name__ , __magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , use_fast=__magic_name__ )
self.assertIsInstance(__magic_name__ , __magic_name__ )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
def lowerCamelCase_ ( self : Optional[int] ):
"""simple docstring"""
with self.assertRaises(__magic_name__ ):
UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" )
# If remote code is disabled, we can't load this config.
with self.assertRaises(__magic_name__ ):
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ )
self.assertTrue(tokenizer.special_attribute_present )
# Test tokenizer can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , trust_remote_code=__magic_name__ )
self.assertTrue(reloaded_tokenizer.special_attribute_present )
if is_tokenizers_available():
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" )
self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizerFast""" )
# Test we can also load the slow version
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ , use_fast=__magic_name__ )
self.assertTrue(tokenizer.special_attribute_present )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
# Test tokenizer can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(__magic_name__ )
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , trust_remote_code=__magic_name__ , use_fast=__magic_name__ )
self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" )
self.assertTrue(reloaded_tokenizer.special_attribute_present )
else:
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" )
@require_tokenizers
def lowerCamelCase_ ( self : Optional[int] ):
"""simple docstring"""
class UpperCAmelCase ( __snake_case ):
lowercase = False
class UpperCAmelCase ( __snake_case ):
lowercase = NewTokenizer
lowercase = False
try:
AutoConfig.register("""custom""" , __magic_name__ )
AutoTokenizer.register(__magic_name__ , slow_tokenizer_class=__magic_name__ )
AutoTokenizer.register(__magic_name__ , fast_tokenizer_class=__magic_name__ )
# If remote code is not set, the default is to use local
UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" )
self.assertFalse(tokenizer.special_attribute_present )
UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , use_fast=__magic_name__ )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
self.assertFalse(tokenizer.special_attribute_present )
# If remote code is disabled, we load the local one.
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" )
self.assertFalse(tokenizer.special_attribute_present )
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ , use_fast=__magic_name__ )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
self.assertFalse(tokenizer.special_attribute_present )
# If remote is enabled, we load from the Hub
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" )
self.assertTrue(tokenizer.special_attribute_present )
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=__magic_name__ , use_fast=__magic_name__ )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
self.assertTrue(tokenizer.special_attribute_present )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
def lowerCamelCase_ ( self : Any ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=__magic_name__ )
self.assertTrue(tokenizer.special_attribute_present )
if is_tokenizers_available():
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" )
# Test we can also load the slow version
UpperCamelCase = AutoTokenizer.from_pretrained(
"""hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=__magic_name__ , use_fast=__magic_name__ )
self.assertTrue(tokenizer.special_attribute_present )
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
else:
self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" )
def lowerCamelCase_ ( self : Any ):
"""simple docstring"""
with self.assertRaisesRegex(
__magic_name__ , """bert-base is not a local folder and is not a valid model identifier""" ):
UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base""" )
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(
__magic_name__ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ):
UpperCamelCase = AutoTokenizer.from_pretrained(__magic_name__ , revision="""aaaaaa""" )
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" )
with RequestCounter() as counter:
UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" )
self.assertEqual(counter.get_request_count , 0 )
self.assertEqual(counter.head_request_count , 1 )
self.assertEqual(counter.other_request_count , 0 )
| 386 |
import os
from collections import namedtuple
import pytest
from datasets import ClassLabel, Features, Sequence, Value
from datasets.commands.test import TestCommand
from datasets.info import DatasetInfo, DatasetInfosDict
__snake_case = namedtuple(
"_TestCommandArgs",
[
"dataset",
"name",
"cache_dir",
"data_dir",
"all_configs",
"save_infos",
"ignore_verifications",
"force_redownload",
"clear_cache",
],
defaults=[None, None, None, False, False, False, False, False],
)
def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ):
"""simple docstring"""
return (abs(source - target ) / target) < 0.01
@pytest.mark.integration
def _lowercase ( SCREAMING_SNAKE_CASE_ : Any ):
"""simple docstring"""
UpperCamelCase = _TestCommandArgs(dataset=SCREAMING_SNAKE_CASE_ , all_configs=SCREAMING_SNAKE_CASE_ , save_infos=SCREAMING_SNAKE_CASE_ )
UpperCamelCase = TestCommand(*SCREAMING_SNAKE_CASE_ )
test_command.run()
UpperCamelCase = os.path.join(SCREAMING_SNAKE_CASE_ , """README.md""" )
assert os.path.exists(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = DatasetInfosDict(
{
"""default""": DatasetInfo(
features=Features(
{
"""tokens""": Sequence(Value("""string""" ) ),
"""ner_tags""": Sequence(
ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ),
"""langs""": Sequence(Value("""string""" ) ),
"""spans""": Sequence(Value("""string""" ) ),
} ) , splits=[
{
"""name""": """train""",
"""num_bytes""": 2_351_563,
"""num_examples""": 10_000,
},
{
"""name""": """validation""",
"""num_bytes""": 238_418,
"""num_examples""": 1_000,
},
] , download_size=3_940_680 , dataset_size=2_589_981 , )
} )
assert dataset_infos.keys() == expected_dataset_infos.keys()
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
UpperCamelCase , UpperCamelCase = getattr(dataset_infos["""default"""] , SCREAMING_SNAKE_CASE_ ), getattr(expected_dataset_infos["""default"""] , SCREAMING_SNAKE_CASE_ )
if key == "num_bytes":
assert is_apercent_close(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
elif key == "splits":
assert list(SCREAMING_SNAKE_CASE_ ) == list(SCREAMING_SNAKE_CASE_ )
for split in result:
assert result[split].name == expected[split].name
assert result[split].num_examples == expected[split].num_examples
assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes )
else:
result == expected
| 386 | 1 |
import logging
import random
import ray
from transformers import RagConfig, RagRetriever, RagTokenizer
from transformers.models.rag.retrieval_rag import CustomHFIndex
_a = logging.getLogger(__name__)
class __A :
'''simple docstring'''
def __init__( self ):
'''simple docstring'''
lowerCamelCase__ = False
def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
'''simple docstring'''
if not self.initialized:
lowerCamelCase__ = RagRetriever(
__lowerCAmelCase , question_encoder_tokenizer=__lowerCAmelCase , generator_tokenizer=__lowerCAmelCase , index=__lowerCAmelCase , init_retrieval=__lowerCAmelCase , )
lowerCamelCase__ = True
def __lowerCamelCase ( self ):
'''simple docstring'''
self.retriever.index.init_index()
def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ):
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__ = self.retriever._main_retrieve(__lowerCAmelCase , __lowerCAmelCase )
return doc_ids, retrieved_doc_embeds
class __A ( lowerCAmelCase ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None ):
'''simple docstring'''
if index is not None and index.is_initialized() and len(__lowerCAmelCase ) > 0:
raise ValueError(
'''When using Ray for distributed fine-tuning, '''
'''you\'ll need to provide the paths instead, '''
'''as the dataset and the index are loaded '''
'''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' )
super().__init__(
__lowerCAmelCase , question_encoder_tokenizer=__lowerCAmelCase , generator_tokenizer=__lowerCAmelCase , index=__lowerCAmelCase , init_retrieval=__lowerCAmelCase , )
lowerCamelCase__ = retrieval_workers
if len(self.retrieval_workers ) > 0:
ray.get(
[
worker.create_rag_retriever.remote(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
for worker in self.retrieval_workers
] )
def __lowerCamelCase ( self ):
'''simple docstring'''
logger.info('''initializing retrieval''' )
if len(self.retrieval_workers ) > 0:
ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] )
else:
# Non-distributed training. Load index into this same process.
self.index.init_index()
def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ):
'''simple docstring'''
if len(self.retrieval_workers ) > 0:
# Select a random retrieval actor.
lowerCamelCase__ = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )]
lowerCamelCase__ , lowerCamelCase__ = ray.get(random_worker.retrieve.remote(__lowerCAmelCase , __lowerCAmelCase ) )
else:
lowerCamelCase__ , lowerCamelCase__ = self._main_retrieve(__lowerCAmelCase , __lowerCAmelCase )
return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCAmelCase )
@classmethod
def __lowerCamelCase ( cls , __lowerCAmelCase , __lowerCAmelCase=None , **__lowerCAmelCase ):
'''simple docstring'''
return super(__lowerCAmelCase , cls ).get_tokenizers(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase )
@classmethod
def __lowerCamelCase ( cls , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , **__lowerCAmelCase ):
'''simple docstring'''
lowerCamelCase__ = kwargs.pop('''config''' , __lowerCAmelCase ) or RagConfig.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
lowerCamelCase__ = RagTokenizer.from_pretrained(__lowerCAmelCase , config=__lowerCAmelCase )
lowerCamelCase__ = rag_tokenizer.question_encoder
lowerCamelCase__ = rag_tokenizer.generator
if indexed_dataset is not None:
lowerCamelCase__ = '''custom'''
lowerCamelCase__ = CustomHFIndex(config.retrieval_vector_size , __lowerCAmelCase )
else:
lowerCamelCase__ = cls._build_index(__lowerCAmelCase )
return cls(
__lowerCAmelCase , question_encoder_tokenizer=__lowerCAmelCase , generator_tokenizer=__lowerCAmelCase , retrieval_workers=__lowerCAmelCase , index=__lowerCAmelCase , )
| 29 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
_a = {
"configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST",
"GPTNeoForCausalLM",
"GPTNeoForQuestionAnswering",
"GPTNeoForSequenceClassification",
"GPTNeoForTokenClassification",
"GPTNeoModel",
"GPTNeoPreTrainedModel",
"load_tf_weights_in_gpt_neo",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"FlaxGPTNeoForCausalLM",
"FlaxGPTNeoModel",
"FlaxGPTNeoPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neo import (
GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoForCausalLM,
GPTNeoForQuestionAnswering,
GPTNeoForSequenceClassification,
GPTNeoForTokenClassification,
GPTNeoModel,
GPTNeoPreTrainedModel,
load_tf_weights_in_gpt_neo,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel
else:
import sys
_a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 29 | 1 |
def UpperCamelCase( __UpperCamelCase : str ):
lowerCAmelCase_ : int = hex_num.strip()
if not hex_num:
raise ValueError('''No value was passed to the function''' )
lowerCAmelCase_ : Dict = hex_num[0] == '''-'''
if is_negative:
lowerCAmelCase_ : Union[str, Any] = hex_num[1:]
try:
lowerCAmelCase_ : List[Any] = int(__UpperCamelCase ,16 )
except ValueError:
raise ValueError('''Invalid value was passed to the function''' )
lowerCAmelCase_ : Any = ''''''
while int_num > 0:
lowerCAmelCase_ : List[str] = str(int_num % 2 ) + bin_str
int_num >>= 1
return int(('''-''' + bin_str) if is_negative else bin_str )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 171 |
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
A__ : Tuple = TypeVar('''KEY''')
A__ : List[Any] = TypeVar('''VAL''')
@dataclass(frozen=UpperCamelCase_ ,slots=UpperCamelCase_ )
class __snake_case ( Generic[KEY, VAL] ):
_a = 42
_a = 42
class __snake_case ( _Item ):
def __init__( self : Union[str, Any]):
super().__init__(A_ , A_)
def __bool__( self : int):
return False
A__ : Optional[int] = _DeletedItem()
class __snake_case ( MutableMapping[KEY, VAL] ):
def __init__( self : Optional[Any] , A_ : int = 8 , A_ : float = 0.75):
lowerCAmelCase_ : Optional[Any] = initial_block_size
lowerCAmelCase_ : list[_Item | None] = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
lowerCAmelCase_ : str = capacity_factor
lowerCAmelCase_ : Union[str, Any] = 0
def UpperCAmelCase__ ( self : str , A_ : KEY):
return hash(A_) % len(self._buckets)
def UpperCAmelCase__ ( self : Union[str, Any] , A_ : int):
return (ind + 1) % len(self._buckets)
def UpperCAmelCase__ ( self : Tuple , A_ : int , A_ : KEY , A_ : VAL):
lowerCAmelCase_ : str = self._buckets[ind]
if not stored:
lowerCAmelCase_ : Optional[int] = _Item(A_ , A_)
self._len += 1
return True
elif stored.key == key:
lowerCAmelCase_ : Union[str, Any] = _Item(A_ , A_)
return True
else:
return False
def UpperCAmelCase__ ( self : Tuple):
lowerCAmelCase_ : List[Any] = len(self._buckets) * self._capacity_factor
return len(self) >= int(A_)
def UpperCAmelCase__ ( self : List[Any]):
if len(self._buckets) <= self._initial_block_size:
return False
lowerCAmelCase_ : Any = len(self._buckets) * self._capacity_factor / 2
return len(self) < limit
def UpperCAmelCase__ ( self : Optional[Any] , A_ : int):
lowerCAmelCase_ : List[str] = self._buckets
lowerCAmelCase_ : str = [None] * new_size
lowerCAmelCase_ : Optional[Any] = 0
for item in old_buckets:
if item:
self._add_item(item.key , item.val)
def UpperCAmelCase__ ( self : int):
self._resize(len(self._buckets) * 2)
def UpperCAmelCase__ ( self : Dict):
self._resize(len(self._buckets) // 2)
def UpperCAmelCase__ ( self : List[str] , A_ : KEY):
lowerCAmelCase_ : str = self._get_bucket_index(A_)
for _ in range(len(self._buckets)):
yield ind
lowerCAmelCase_ : Tuple = self._get_next_ind(A_)
def UpperCAmelCase__ ( self : List[Any] , A_ : KEY , A_ : VAL):
for ind in self._iterate_buckets(A_):
if self._try_set(A_ , A_ , A_):
break
def __setitem__( self : int , A_ : KEY , A_ : VAL):
if self._is_full():
self._size_up()
self._add_item(A_ , A_)
def __delitem__( self : Tuple , A_ : KEY):
for ind in self._iterate_buckets(A_):
lowerCAmelCase_ : Tuple = self._buckets[ind]
if item is None:
raise KeyError(A_)
if item is _deleted:
continue
if item.key == key:
lowerCAmelCase_ : Dict = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__( self : List[str] , A_ : KEY):
for ind in self._iterate_buckets(A_):
lowerCAmelCase_ : Tuple = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(A_)
def __len__( self : Dict):
return self._len
def __iter__( self : Dict):
yield from (item.key for item in self._buckets if item)
def __repr__( self : Optional[Any]):
lowerCAmelCase_ : List[Any] = ''' ,'''.join(
F"""{item.key}: {item.val}""" for item in self._buckets if item)
return F"""HashMap({val_string})"""
| 171 | 1 |
import os
import tempfile
import unittest
import uuid
from pathlib import Path
from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision
from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText
from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available
if is_torch_available():
import torch
if is_soundfile_availble():
import soundfile as sf
if is_vision_available():
from PIL import Image
def _lowercase ( __lowerCAmelCase="" ) -> int:
SCREAMING_SNAKE_CASE__ : str = tempfile.mkdtemp()
return os.path.join(_lowerCamelCase , str(uuid.uuida() ) + suffix )
@require_soundfile
@require_torch
class __a (unittest.TestCase):
'''simple docstring'''
def _a ( self ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = torch.rand(12 , dtype=torch.floataa ) - 0.5
SCREAMING_SNAKE_CASE__ : str = AgentAudio(_lowercase )
SCREAMING_SNAKE_CASE__ : Optional[int] = str(agent_type.to_string() )
# Ensure that the tensor and the agent_type's tensor are the same
self.assertTrue(torch.allclose(_lowercase , agent_type.to_raw() , atol=1E-4 ) )
del agent_type
# Ensure the path remains even after the object deletion
self.assertTrue(os.path.exists(_lowercase ) )
# Ensure that the file contains the same value as the original tensor
SCREAMING_SNAKE_CASE__ : str = sf.read(_lowercase )
self.assertTrue(torch.allclose(_lowercase , torch.tensor(_lowercase ) , atol=1E-4 ) )
def _a ( self ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[int] = torch.rand(12 , dtype=torch.floataa ) - 0.5
SCREAMING_SNAKE_CASE__ : Optional[int] = get_new_path(suffix=""".wav""" )
sf.write(_lowercase , _lowercase , 16_000 )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = AgentAudio(_lowercase )
self.assertTrue(torch.allclose(_lowercase , agent_type.to_raw() , atol=1E-4 ) )
self.assertEqual(agent_type.to_string() , _lowercase )
@require_vision
@require_torch
class __a (unittest.TestCase):
'''simple docstring'''
def _a ( self ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = torch.randint(0 , 256 , (64, 64, 3) )
SCREAMING_SNAKE_CASE__ : Dict = AgentImage(_lowercase )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = str(agent_type.to_string() )
# Ensure that the tensor and the agent_type's tensor are the same
self.assertTrue(torch.allclose(_lowercase , agent_type._tensor , atol=1E-4 ) )
self.assertIsInstance(agent_type.to_raw() , Image.Image )
# Ensure the path remains even after the object deletion
del agent_type
self.assertTrue(os.path.exists(_lowercase ) )
def _a ( self ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png"""
SCREAMING_SNAKE_CASE__ : List[str] = Image.open(_lowercase )
SCREAMING_SNAKE_CASE__ : Optional[int] = AgentImage(_lowercase )
self.assertTrue(path.samefile(agent_type.to_string() ) )
self.assertTrue(image == agent_type.to_raw() )
# Ensure the path remains even after the object deletion
del agent_type
self.assertTrue(os.path.exists(_lowercase ) )
def _a ( self ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png"""
SCREAMING_SNAKE_CASE__ : List[str] = Image.open(_lowercase )
SCREAMING_SNAKE_CASE__ : str = AgentImage(_lowercase )
self.assertFalse(path.samefile(agent_type.to_string() ) )
self.assertTrue(image == agent_type.to_raw() )
# Ensure the path remains even after the object deletion
del agent_type
self.assertTrue(os.path.exists(_lowercase ) )
class __a (unittest.TestCase):
'''simple docstring'''
def _a ( self ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[Any] = """Hey!"""
SCREAMING_SNAKE_CASE__ : int = AgentText(_lowercase )
self.assertEqual(_lowercase , agent_type.to_string() )
self.assertEqual(_lowercase , agent_type.to_raw() )
self.assertEqual(_lowercase , _lowercase )
| 718 |
"""simple docstring"""
import tempfile
import unittest
from transformers import TaConfig, is_torch_available
from transformers.testing_utils import (
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
torch_device,
)
from ...generation.test_utils import GenerationTesterMixin
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel
class __a :
'''simple docstring'''
def __init__( self , _a , _a=99 , _a=13 , _a=7 , _a=9 , _a=True , _a=True , _a=False , _a=32 , _a=5 , _a=4 , _a=37 , _a=8 , _a=0.1 , _a=0.002 , _a=1 , _a=0 , _a=0 , _a=None , _a=None , ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = parent
SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size
SCREAMING_SNAKE_CASE__ : Tuple = encoder_seq_length
SCREAMING_SNAKE_CASE__ : str = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE__ : Optional[int] = self.decoder_seq_length
SCREAMING_SNAKE_CASE__ : Tuple = is_training
SCREAMING_SNAKE_CASE__ : Dict = use_attention_mask
SCREAMING_SNAKE_CASE__ : List[str] = use_labels
SCREAMING_SNAKE_CASE__ : str = vocab_size
SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size
SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers
SCREAMING_SNAKE_CASE__ : Any = num_attention_heads
SCREAMING_SNAKE_CASE__ : Any = d_ff
SCREAMING_SNAKE_CASE__ : Any = relative_attention_num_buckets
SCREAMING_SNAKE_CASE__ : Union[str, Any] = dropout_rate
SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor
SCREAMING_SNAKE_CASE__ : List[Any] = eos_token_id
SCREAMING_SNAKE_CASE__ : List[str] = pad_token_id
SCREAMING_SNAKE_CASE__ : Any = decoder_start_token_id
SCREAMING_SNAKE_CASE__ : Any = None
SCREAMING_SNAKE_CASE__ : str = decoder_layers
def _a ( self ) -> Tuple:
"""simple docstring"""
return TaConfig.from_pretrained("""google/umt5-base""" )
def _a ( self , _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> Any:
"""simple docstring"""
if attention_mask is None:
SCREAMING_SNAKE_CASE__ : List[str] = input_ids.ne(config.pad_token_id )
if decoder_attention_mask is None:
SCREAMING_SNAKE_CASE__ : int = decoder_input_ids.ne(config.pad_token_id )
if head_mask is None:
SCREAMING_SNAKE_CASE__ : str = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_a )
if decoder_head_mask is None:
SCREAMING_SNAKE_CASE__ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_a )
if cross_attn_head_mask is None:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.ones(
config.num_decoder_layers , config.num_attention_heads , device=_a )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
def _a ( self ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size )
# we need to clamp the input ids here to avoid having pad token in between
# this is because for NllbMoe the position_ids are prepared such that
# all pad tokens have pos id = 2 and rest are between 2..seq_length
# and the seq_length here is seq_length - num_pad_tokens
# but when using past, there is no way of knowing if the past input ids had
# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
# position_ids being off by num_pad_tokens in past input
SCREAMING_SNAKE_CASE__ : Tuple = input_ids.clamp(self.pad_token_id + 1 )
SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_input_ids.clamp(self.pad_token_id + 1 )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_config()
SCREAMING_SNAKE_CASE__ : List[str] = config.num_attention_heads
SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_inputs_dict(_a , _a , _a )
return config, input_dict
def _a ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs()
return config, inputs_dict
def _a ( self ) -> List[str]:
"""simple docstring"""
return TaConfig(
vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , )
def _a ( self ) -> List[Any]:
"""simple docstring"""
return TaConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , )
def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = UMTaModel(config=_a )
model.to(_a )
model.eval()
SCREAMING_SNAKE_CASE__ : Dict = model(
input_ids=_a , decoder_input_ids=_a , attention_mask=_a , decoder_attention_mask=_a , )
SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=_a , decoder_input_ids=_a )
SCREAMING_SNAKE_CASE__ : Optional[Any] = result.last_hidden_state
SCREAMING_SNAKE_CASE__ : Dict = result.past_key_values
SCREAMING_SNAKE_CASE__ : Any = result.encoder_last_hidden_state
self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) )
self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) )
# There should be `num_layers` key value embeddings stored in decoder_past
self.parent.assertEqual(len(_a ) , config.num_layers )
# There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
self.parent.assertEqual(len(decoder_past[0] ) , 4 )
def _a ( self , _a , _a , _a , _a , _a , _a , ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).get_decoder().to(_a ).eval()
# first forward pass
SCREAMING_SNAKE_CASE__ : str = model(_a , use_cache=_a )
SCREAMING_SNAKE_CASE__ : str = model(_a )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a , use_cache=_a )
self.parent.assertTrue(len(_a ) == len(_a ) )
self.parent.assertTrue(len(_a ) == len(_a ) + 1 )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size )
# append to next input_ids and
SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_a )["""last_hidden_state"""]
SCREAMING_SNAKE_CASE__ : Tuple = model(_a , past_key_values=_a )["""last_hidden_state"""]
# select random slice
SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor((1,) , output_from_past.shape[-1] ).item()
SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE__ : List[Any] = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(_a , _a , atol=1E-3 ) )
def _a ( self , _a , _a , ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = UMTaModel(config=_a ).to(_a ).half().eval()
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**_a )["""last_hidden_state"""]
self.parent.assertFalse(torch.isnan(_a ).any().item() )
@require_torch
class __a (UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase):
'''simple docstring'''
_SCREAMING_SNAKE_CASE :Union[str, Any] = (
(UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else ()
)
_SCREAMING_SNAKE_CASE :Optional[int] = (UMTaForConditionalGeneration,) if is_torch_available() else ()
_SCREAMING_SNAKE_CASE :List[str] = (
{
"""conversational""": UMTaForConditionalGeneration,
"""feature-extraction""": UMTaModel,
"""summarization""": UMTaForConditionalGeneration,
"""text2text-generation""": UMTaForConditionalGeneration,
"""translation""": UMTaForConditionalGeneration,
"""question-answering""": UMTaForQuestionAnswering,
}
if is_torch_available()
else {}
)
_SCREAMING_SNAKE_CASE :Union[str, Any] = True
_SCREAMING_SNAKE_CASE :Tuple = False
_SCREAMING_SNAKE_CASE :Optional[Any] = False
_SCREAMING_SNAKE_CASE :List[Any] = True
_SCREAMING_SNAKE_CASE :List[str] = True
# The small UMT5 model needs higher percentages for CPU/MP tests
_SCREAMING_SNAKE_CASE :Union[str, Any] = [0.8, 0.9]
def _a ( self ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = UMTaModelTester(self )
@unittest.skip("""Test has a segmentation fault on torch 1.8.0""" )
def _a ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : Dict = UMTaModel(config_and_inputs[0] ).to(_a )
with tempfile.TemporaryDirectory() as tmpdirname:
torch.onnx.export(
_a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=_a , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , )
@unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" )
def _a ( self ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_fpaa_forward(*_a )
def _a ( self ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""]
SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs[0]
SCREAMING_SNAKE_CASE__ : Tuple = UMTaForConditionalGeneration(_a ).eval()
model.to(_a )
SCREAMING_SNAKE_CASE__ : List[str] = {
"""head_mask""": torch.zeros(config.num_layers , config.num_heads , device=_a ),
"""decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ),
"""cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=_a ),
}
for attn_name, (name, mask) in zip(_a , head_masking.items() ):
SCREAMING_SNAKE_CASE__ : List[str] = {name: mask}
# Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
if name == "head_mask":
SCREAMING_SNAKE_CASE__ : str = torch.ones(
config.num_decoder_layers , config.num_heads , device=_a )
SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate(
config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=_a , return_dict_in_generate=_a , **_a , )
# We check the state of decoder_attentions and cross_attentions just from the last step
SCREAMING_SNAKE_CASE__ : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 )
@unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" )
def _a ( self ) -> Dict:
"""simple docstring"""
pass
@require_torch
@require_sentencepiece
@require_tokenizers
class __a (unittest.TestCase):
'''simple docstring'''
@slow
@unittest.skip(
"""Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" )
def _a ( self ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=_a ).to(_a )
SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=_a , legacy=_a )
SCREAMING_SNAKE_CASE__ : Optional[Any] = [
"""Bonjour monsieur <extra_id_0> bien <extra_id_1>.""",
"""No se como puedo <extra_id_0>.""",
"""This is the reason why we <extra_id_0> them.""",
"""The <extra_id_0> walks in <extra_id_1>, seats""",
"""A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""",
]
SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(_a , return_tensors="""pt""" , padding=_a ).input_ids
# fmt: off
SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor(
[
[ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0],
[ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1],
] )
# fmt: on
torch.testing.assert_allclose(_a , _a )
SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids.to(_a ) )
SCREAMING_SNAKE_CASE__ : int = [
"""<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""",
"""<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
"""<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
"""<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
"""<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
]
SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.batch_decode(_a )
self.assertEqual(_a , _a )
| 12 | 0 |
'''simple docstring'''
from typing import Any
def lowerCamelCase__ ( a__ , a__ , a__ , a__ , a__ , ) -> list:
"""simple docstring"""
_validation(
a__ , a__ , a__ , a__ , a__ , )
# Creates data structures and fill initial step
_snake_case : dict = {}
_snake_case : dict = {}
for state in states_space:
_snake_case : int = observations_space[0]
_snake_case : int = (
initial_probabilities[state] * emission_probabilities[state][observation]
)
_snake_case : Optional[Any] = None
# Fills the data structure with the probabilities of
# different transitions and pointers to previous states
for o in range(1 , len(a__)):
_snake_case : Any = observations_space[o]
_snake_case : Union[str, Any] = observations_space[o - 1]
for state in states_space:
# Calculates the argmax for probability function
_snake_case : Optional[Any] = ''
_snake_case : List[Any] = -1
for k_state in states_space:
_snake_case : Tuple = (
probabilities[(k_state, prior_observation)]
* transition_probabilities[k_state][state]
* emission_probabilities[state][observation]
)
if probability > max_probability:
_snake_case : List[str] = probability
_snake_case : Optional[Any] = k_state
# Update probabilities and pointers dicts
_snake_case : str = (
probabilities[(arg_max, prior_observation)]
* transition_probabilities[arg_max][state]
* emission_probabilities[state][observation]
)
_snake_case : Union[str, Any] = arg_max
# The final observation
_snake_case : List[Any] = observations_space[len(a__) - 1]
# argmax for given final observation
_snake_case : Any = ''
_snake_case : Tuple = -1
for k_state in states_space:
_snake_case : Any = probabilities[(k_state, final_observation)]
if probability > max_probability:
_snake_case : Dict = probability
_snake_case : int = k_state
_snake_case : List[Any] = arg_max
# Process pointers backwards
_snake_case : str = last_state
_snake_case : Union[str, Any] = []
for o in range(len(a__) - 1 , -1 , -1):
result.append(a__)
_snake_case : Dict = pointers[previous, observations_space[o]]
result.reverse()
return result
def lowerCamelCase__ ( a__ , a__ , a__ , a__ , a__ , ) -> None:
"""simple docstring"""
_validate_not_empty(
a__ , a__ , a__ , a__ , a__ , )
_validate_lists(a__ , a__)
_validate_dicts(
a__ , a__ , a__)
def lowerCamelCase__ ( a__ , a__ , a__ , a__ , a__ , ) -> None:
"""simple docstring"""
if not all(
[
observations_space,
states_space,
initial_probabilities,
transition_probabilities,
emission_probabilities,
]):
raise ValueError('There\'s an empty parameter')
def lowerCamelCase__ ( a__ , a__) -> None:
"""simple docstring"""
_validate_list(a__ , 'observations_space')
_validate_list(a__ , 'states_space')
def lowerCamelCase__ ( a__ , a__) -> None:
"""simple docstring"""
if not isinstance(_object , a__):
_snake_case : int = F"""{var_name} must be a list"""
raise ValueError(a__)
else:
for x in _object:
if not isinstance(a__ , a__):
_snake_case : Dict = F"""{var_name} must be a list of strings"""
raise ValueError(a__)
def lowerCamelCase__ ( a__ , a__ , a__ , ) -> None:
"""simple docstring"""
_validate_dict(a__ , 'initial_probabilities' , a__)
_validate_nested_dict(a__ , 'transition_probabilities')
_validate_nested_dict(a__ , 'emission_probabilities')
def lowerCamelCase__ ( a__ , a__) -> None:
"""simple docstring"""
_validate_dict(_object , a__ , a__)
for x in _object.values():
_validate_dict(a__ , a__ , a__ , a__)
def lowerCamelCase__ ( a__ , a__ , a__ , a__ = False) -> None:
"""simple docstring"""
if not isinstance(_object , a__):
_snake_case : Optional[int] = F"""{var_name} must be a dict"""
raise ValueError(a__)
if not all(isinstance(a__ , a__) for x in _object):
_snake_case : List[Any] = F"""{var_name} all keys must be strings"""
raise ValueError(a__)
if not all(isinstance(a__ , a__) for x in _object.values()):
_snake_case : int = 'nested dictionary ' if nested else ''
_snake_case : Tuple = F"""{var_name} {nested_text}all values must be {value_type.__name__}"""
raise ValueError(a__)
if __name__ == "__main__":
from doctest import testmod
testmod()
| 517 | from __future__ import annotations
def A__ ( lowercase: int | str ) -> bool:
A : int =str(lowercase )
return n == n[::-1]
def A__ ( lowercase: int = 1_000_000 ) -> Any:
A : str =0
for i in range(1, lowercase ):
if is_palindrome(lowercase ) and is_palindrome(bin(lowercase ).split('b' )[1] ):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| 305 | 0 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
_lowerCamelCase = datasets.utils.logging.get_logger(__name__)
@dataclass
class UpperCAmelCase__ ( datasets.BuilderConfig ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE : Optional[datasets.Features] = None
_SCREAMING_SNAKE_CASE : str = "utf-8"
_SCREAMING_SNAKE_CASE : Optional[str] = None
_SCREAMING_SNAKE_CASE : Optional[str] = None
_SCREAMING_SNAKE_CASE : bool = True # deprecated
_SCREAMING_SNAKE_CASE : Optional[int] = None # deprecated
_SCREAMING_SNAKE_CASE : int = 10 << 20 # 10MB
_SCREAMING_SNAKE_CASE : Optional[bool] = None
class UpperCAmelCase__ ( datasets.ArrowBasedBuilder ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE : Union[str, Any] = JsonConfig
def lowerCAmelCase__ ( self ):
if self.config.block_size is not None:
logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" )
a =self.config.block_size
if self.config.use_threads is not True:
logger.warning(
"""The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" )
if self.config.newlines_in_values is not None:
raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" )
return datasets.DatasetInfo(features=self.config.features )
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
if not self.config.data_files:
raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
a =dl_manager.download_and_extract(self.config.data_files )
if isinstance(_lowerCAmelCase , (str, list, tuple) ):
a =data_files
if isinstance(_lowerCAmelCase , _lowerCAmelCase ):
a =[files]
a =[dl_manager.iter_files(_lowerCAmelCase ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )]
a =[]
for split_name, files in data_files.items():
if isinstance(_lowerCAmelCase , _lowerCAmelCase ):
a =[files]
a =[dl_manager.iter_files(_lowerCAmelCase ) for file in files]
splits.append(datasets.SplitGenerator(name=_lowerCAmelCase , gen_kwargs={"""files""": files} ) )
return splits
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features ) - set(pa_table.column_names ):
a =self.config.features.arrow_schema.field(_lowerCAmelCase ).type
a =pa_table.append_column(_lowerCAmelCase , pa.array([None] * len(_lowerCAmelCase ) , type=_lowerCAmelCase ) )
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
a =table_cast(_lowerCAmelCase , self.config.features.arrow_schema )
return pa_table
def lowerCAmelCase__ ( self , _lowerCAmelCase ):
for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCAmelCase ) ):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(_lowerCAmelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
a =json.load(_lowerCAmelCase )
# We keep only the field we are interested in
a =dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(_lowerCAmelCase , (list, tuple) ):
a =set().union(*[row.keys() for row in dataset] )
a ={col: [row.get(_lowerCAmelCase ) for row in dataset] for col in keys}
else:
a =dataset
a =pa.Table.from_pydict(_lowerCAmelCase )
yield file_idx, self._cast_table(_lowerCAmelCase )
# If the file has one json object per line
else:
with open(_lowerCAmelCase , """rb""" ) as f:
a =0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
a =max(self.config.chunksize // 32 , 16 << 10 )
a =(
self.config.encoding_errors if self.config.encoding_errors is not None else """strict"""
)
while True:
a =f.read(self.config.chunksize )
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(_lowerCAmelCase )
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
a =batch.decode(self.config.encoding , errors=_lowerCAmelCase ).encode("""utf-8""" )
try:
while True:
try:
a =paj.read_json(
io.BytesIO(_lowerCAmelCase ) , read_options=paj.ReadOptions(block_size=_lowerCAmelCase ) )
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(_lowerCAmelCase , pa.ArrowInvalid )
and "straddling" not in str(_lowerCAmelCase )
or block_size > len(_lowerCAmelCase )
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
F'''Batch of {len(_lowerCAmelCase )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.''' )
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
_lowerCAmelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f:
a =json.load(_lowerCAmelCase )
except json.JSONDecodeError:
logger.error(F'''Failed to read file \'{file}\' with error {type(_lowerCAmelCase )}: {e}''' )
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(_lowerCAmelCase , _lowerCAmelCase ): # list is the only sequence type supported in JSON
try:
a =set().union(*[row.keys() for row in dataset] )
a ={col: [row.get(_lowerCAmelCase ) for row in dataset] for col in keys}
a =pa.Table.from_pydict(_lowerCAmelCase )
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(F'''Failed to read file \'{file}\' with error {type(_lowerCAmelCase )}: {e}''' )
raise ValueError(F'''Not able to read records in the JSON file at {file}.''' ) from None
yield file_idx, self._cast_table(_lowerCAmelCase )
break
else:
logger.error(F'''Failed to read file \'{file}\' with error {type(_lowerCAmelCase )}: {e}''' )
raise ValueError(
F'''Not able to read records in the JSON file at {file}. '''
F'''You should probably indicate the field of the JSON file containing your records. '''
F'''This JSON file contain the following fields: {str(list(dataset.keys() ) )}. '''
F'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ''' ) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_lowerCAmelCase )
batch_idx += 1
| 321 |
import inspect
import unittest
from typing import List
import numpy as np
from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
)
from transformers.models.efficientformer.modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_vision_available():
from PIL import Image
from transformers import EfficientFormerImageProcessor
class UpperCAmelCase__ :
'''simple docstring'''
def __init__( self , _lowerCAmelCase , _lowerCAmelCase = 13 , _lowerCAmelCase = 64 , _lowerCAmelCase = 2 , _lowerCAmelCase = 3 , _lowerCAmelCase = 3 , _lowerCAmelCase = True , _lowerCAmelCase = True , _lowerCAmelCase = 128 , _lowerCAmelCase=[16, 32, 64, 128] , _lowerCAmelCase = 7 , _lowerCAmelCase = 4 , _lowerCAmelCase = 37 , _lowerCAmelCase = "gelu" , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 10 , _lowerCAmelCase = 0.02 , _lowerCAmelCase = 2 , _lowerCAmelCase = 1 , _lowerCAmelCase = 128 , _lowerCAmelCase = [2, 2, 2, 2] , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , ):
a =parent
a =batch_size
a =image_size
a =patch_size
a =num_channels
a =is_training
a =use_labels
a =hidden_size
a =num_hidden_layers
a =num_attention_heads
a =intermediate_size
a =hidden_act
a =hidden_dropout_prob
a =attention_probs_dropout_prob
a =type_sequence_label_size
a =initializer_range
a =encoder_stride
a =num_attention_outputs
a =embed_dim
a =embed_dim + 1
a =resolution
a =depths
a =hidden_sizes
a =dim
a =mlp_expansion_ratio
def lowerCAmelCase__ ( self ):
a =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
a =None
if self.use_labels:
a =ids_tensor([self.batch_size] , self.type_sequence_label_size )
a =self.get_config()
return config, pixel_values, labels
def lowerCAmelCase__ ( self ):
return EfficientFormerConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , )
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ):
a =TFEfficientFormerModel(config=_lowerCAmelCase )
a =model(_lowerCAmelCase , training=_lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ):
a =self.type_sequence_label_size
a =TFEfficientFormerForImageClassification(_lowerCAmelCase )
a =model(_lowerCAmelCase , labels=_lowerCAmelCase , training=_lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
a =1
a =TFEfficientFormerForImageClassification(_lowerCAmelCase )
a =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
a =model(_lowerCAmelCase , labels=_lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def lowerCAmelCase__ ( self ):
a =self.prepare_config_and_inputs()
a , a , a =config_and_inputs
a ={"""pixel_values""": pixel_values}
return config, inputs_dict
@require_tf
class UpperCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE : str = (
(
TFEfficientFormerModel,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerForImageClassification,
)
if is_tf_available()
else ()
)
_SCREAMING_SNAKE_CASE : Any = (
{
"feature-extraction": TFEfficientFormerModel,
"image-classification": (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
),
}
if is_tf_available()
else {}
)
_SCREAMING_SNAKE_CASE : int = False
_SCREAMING_SNAKE_CASE : Tuple = False
_SCREAMING_SNAKE_CASE : str = False
_SCREAMING_SNAKE_CASE : Any = False
_SCREAMING_SNAKE_CASE : int = False
def lowerCAmelCase__ ( self ):
a =TFEfficientFormerModelTester(self )
a =ConfigTester(
self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 )
def lowerCAmelCase__ ( self ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" )
def lowerCAmelCase__ ( self ):
pass
@unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" )
def lowerCAmelCase__ ( self ):
pass
def lowerCAmelCase__ ( self ):
a , a =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a =model_class(_lowerCAmelCase )
a =inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a =[*signature.parameters.keys()]
a =["""pixel_values"""]
self.assertListEqual(arg_names[:1] , _lowerCAmelCase )
def lowerCAmelCase__ ( self ):
def check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ):
a =model_class(_lowerCAmelCase )
a =model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) , training=_lowerCAmelCase )
a =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
a =getattr(
self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 )
self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase )
if hasattr(self.model_tester , """encoder_seq_length""" ):
a =self.model_tester.encoder_seq_length
if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1:
a =seq_length * self.model_tester.chunk_length
else:
a =self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , )
if config.is_encoder_decoder:
a =outputs.decoder_hidden_states
self.asseretIsInstance(_lowerCAmelCase , (list, tuple) )
self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase )
a =getattr(self.model_tester , """seq_length""" , _lowerCAmelCase )
a =getattr(self.model_tester , """decoder_seq_length""" , _lowerCAmelCase )
self.assertListEqual(
list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , )
a , a =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a =True
check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
a =True
check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
def lowerCAmelCase__ ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False ):
a =super()._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
if return_labels:
if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def lowerCAmelCase__ ( self ):
a =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCAmelCase )
@unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" )
def lowerCAmelCase__ ( self ):
a =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase )
def lowerCAmelCase__ ( self ):
a =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase )
@slow
def lowerCAmelCase__ ( self ):
for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
a =TFEfficientFormerModel.from_pretrained(_lowerCAmelCase )
self.assertIsNotNone(_lowerCAmelCase )
def lowerCAmelCase__ ( self ):
a , a =self.model_tester.prepare_config_and_inputs_for_common()
a =True
a =getattr(self.model_tester , """seq_length""" , _lowerCAmelCase )
a =getattr(self.model_tester , """encoder_seq_length""" , _lowerCAmelCase )
a =getattr(self.model_tester , """key_length""" , _lowerCAmelCase )
a =getattr(self.model_tester , """chunk_length""" , _lowerCAmelCase )
if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ):
a =encoder_seq_length * self.model_tester.num_hashes
for model_class in self.all_model_classes:
a =True
a =False
a =True
a =model_class(_lowerCAmelCase )
a =model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) , training=_lowerCAmelCase )
a =outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(_lowerCAmelCase ) , self.model_tester.num_attention_outputs )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
a =True
a =model_class(_lowerCAmelCase )
a =model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) , training=_lowerCAmelCase )
a =outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(_lowerCAmelCase ) , self.model_tester.num_attention_outputs )
if chunk_length is not None:
self.assertListEqual(
list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , )
else:
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , )
def lowerCAmelCase__ ( self ):
# We use a simplified version of this test for EfficientFormer because it requires training=False
# and Keras refuses to let us force that during functional construction
a , a =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# Prepare our model
a =model_class(_lowerCAmelCase )
# These are maximally general inputs for the model, with multiple None dimensions
# Hopefully this will catch any conditionals that fail for flexible shapes
a ={
key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=_lowerCAmelCase )
for key, val in model.input_signature.items()
if key in model.dummy_inputs
}
a =model(_lowerCAmelCase )
self.assertTrue(outputs_dict is not None )
def lowerCamelCase ( )-> str:
"""simple docstring"""
a =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_tf
@require_vision
class UpperCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def lowerCAmelCase__ ( self ):
return (
EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" )
if is_vision_available()
else None
)
@slow
def lowerCAmelCase__ ( self ):
a =TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" )
a =self.default_image_processor
a =prepare_img()
a =image_processor(images=_lowerCAmelCase , return_tensors="""tf""" )
# forward pass
a =model(**_lowerCAmelCase , training=_lowerCAmelCase )
# verify the logits
a =tf.TensorShape((1, 1_000) )
self.assertEqual(outputs.logits.shape , _lowerCAmelCase )
a =tf.constant([-0.05_55, 0.48_25, -0.08_52] )
self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1E-4 ) )
@slow
def lowerCAmelCase__ ( self ):
a =TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
"""snap-research/efficientformer-l1-300""" )
a =self.default_image_processor
a =prepare_img()
a =image_processor(images=_lowerCAmelCase , return_tensors="""tf""" )
# forward pass
a =model(**_lowerCAmelCase , training=_lowerCAmelCase )
# verify the logits
a =tf.TensorShape((1, 1_000) )
self.assertEqual(outputs.logits.shape , _lowerCAmelCase )
a =tf.constant([-0.13_12, 0.43_53, -1.04_99] )
self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1E-4 ) )
| 321 | 1 |
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def a__ ( _UpperCamelCase : int ):
__lowerCamelCase = int(number**0.5 )
return number == sq * sq
def a__ ( _UpperCamelCase : int ,_UpperCamelCase : int ,_UpperCamelCase : int ,_UpperCamelCase : int ,_UpperCamelCase : int ,_UpperCamelCase : int ):
__lowerCamelCase = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
__lowerCamelCase = x_den * y_den * z_den
__lowerCamelCase = gcd(_UpperCamelCase ,_UpperCamelCase )
top //= hcf
bottom //= hcf
return top, bottom
def a__ ( _UpperCamelCase : int = 35 ):
__lowerCamelCase = set()
__lowerCamelCase = 42
__lowerCamelCase = Fraction(0 )
__lowerCamelCase = 42
for x_num in range(1 ,order + 1 ):
for x_den in range(x_num + 1 ,order + 1 ):
for y_num in range(1 ,order + 1 ):
for y_den in range(y_num + 1 ,order + 1 ):
# n=1
__lowerCamelCase = x_num * y_den + x_den * y_num
__lowerCamelCase = x_den * y_den
__lowerCamelCase = gcd(_UpperCamelCase ,_UpperCamelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
__lowerCamelCase = add_three(
_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase )
unique_s.add(_UpperCamelCase )
# n=2
__lowerCamelCase = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
__lowerCamelCase = x_den * x_den * y_den * y_den
if is_sq(_UpperCamelCase ) and is_sq(_UpperCamelCase ):
__lowerCamelCase = int(sqrt(_UpperCamelCase ) )
__lowerCamelCase = int(sqrt(_UpperCamelCase ) )
__lowerCamelCase = gcd(_UpperCamelCase ,_UpperCamelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
__lowerCamelCase = add_three(
_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase )
unique_s.add(_UpperCamelCase )
# n=-1
__lowerCamelCase = x_num * y_num
__lowerCamelCase = x_den * y_num + x_num * y_den
__lowerCamelCase = gcd(_UpperCamelCase ,_UpperCamelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
__lowerCamelCase = add_three(
_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase )
unique_s.add(_UpperCamelCase )
# n=2
__lowerCamelCase = x_num * x_num * y_num * y_num
__lowerCamelCase = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(_UpperCamelCase ) and is_sq(_UpperCamelCase ):
__lowerCamelCase = int(sqrt(_UpperCamelCase ) )
__lowerCamelCase = int(sqrt(_UpperCamelCase ) )
__lowerCamelCase = gcd(_UpperCamelCase ,_UpperCamelCase )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
__lowerCamelCase = add_three(
_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase )
unique_s.add(_UpperCamelCase )
for num, den in unique_s:
total += Fraction(_UpperCamelCase ,_UpperCamelCase )
return total.denominator + total.numerator
if __name__ == "__main__":
print(f"{solution() = }")
| 175 |
from __future__ import annotations
from math import ceil, floor, sqrt
def a__ ( _UpperCamelCase : int = 2_00_00_00 ):
__lowerCamelCase = [0]
__lowerCamelCase = 42
for idx in range(1 ,ceil(sqrt(target * 2 ) * 1.1 ) ):
triangle_numbers.append(triangle_numbers[-1] + idx )
# we want this to be as close as possible to target
__lowerCamelCase = 0
# the area corresponding to the grid that gives the product closest to target
__lowerCamelCase = 0
# an estimate of b, using the quadratic formula
__lowerCamelCase = 42
# the largest integer less than b_estimate
__lowerCamelCase = 42
# the largest integer less than b_estimate
__lowerCamelCase = 42
# the triangle number corresponding to b_floor
__lowerCamelCase = 42
# the triangle number corresponding to b_ceil
__lowerCamelCase = 42
for idx_a, triangle_a in enumerate(triangle_numbers[1:] ,1 ):
__lowerCamelCase = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2
__lowerCamelCase = floor(_UpperCamelCase )
__lowerCamelCase = ceil(_UpperCamelCase )
__lowerCamelCase = triangle_numbers[b_floor]
__lowerCamelCase = triangle_numbers[b_ceil]
if abs(target - triangle_b_first_guess * triangle_a ) < abs(
target - best_product ):
__lowerCamelCase = triangle_b_first_guess * triangle_a
__lowerCamelCase = idx_a * b_floor
if abs(target - triangle_b_second_guess * triangle_a ) < abs(
target - best_product ):
__lowerCamelCase = triangle_b_second_guess * triangle_a
__lowerCamelCase = idx_a * b_ceil
return area
if __name__ == "__main__":
print(f"{solution() = }")
| 175 | 1 |
from __future__ import annotations
def UpperCamelCase ( snake_case__ : Dict ):
'''simple docstring'''
return len(set(lowerCamelCase__ ) ) == len(lowerCamelCase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 715 |
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
lowerCamelCase__ = """"""
lowerCamelCase__ = """"""
lowerCamelCase__ = """"""
lowerCamelCase__ = 1 # (0 is vertical, 1 is horizontal)
def UpperCamelCase ( ):
'''simple docstring'''
__snake_case , __snake_case :List[Any] = get_dataset(snake_case__ ,snake_case__ )
print("""Processing...""" )
__snake_case , __snake_case , __snake_case :Tuple = update_image_and_anno(snake_case__ ,snake_case__ ,snake_case__ )
for index, image in enumerate(snake_case__ ):
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
__snake_case :str = random_chars(32 )
__snake_case :Optional[Any] = paths[index].split(os.sep )[-1].rsplit(""".""" ,1 )[0]
__snake_case :List[str] = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}'''
cva.imwrite(f'''/{file_root}.jpg''' ,snake_case__ ,[cva.IMWRITE_JPEG_QUALITY, 85] )
print(f'''Success {index+1}/{len(snake_case__ )} with {file_name}''' )
__snake_case :Optional[int] = []
for anno in new_annos[index]:
__snake_case :str = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}'''
annos_list.append(snake_case__ )
with open(f'''/{file_root}.txt''' ,"""w""" ) as outfile:
outfile.write("""\n""".join(line for line in annos_list ) )
def UpperCamelCase ( snake_case__ : str ,snake_case__ : str ):
'''simple docstring'''
__snake_case :List[str] = []
__snake_case :Dict = []
for label_file in glob.glob(os.path.join(snake_case__ ,"""*.txt""" ) ):
__snake_case :Tuple = label_file.split(os.sep )[-1].rsplit(""".""" ,1 )[0]
with open(snake_case__ ) as in_file:
__snake_case :Optional[int] = in_file.readlines()
__snake_case :Any = os.path.join(snake_case__ ,f'''{label_name}.jpg''' )
__snake_case :List[str] = []
for obj_list in obj_lists:
__snake_case :int = obj_list.rstrip("""\n""" ).split(""" """ )
boxes.append(
[
int(obj[0] ),
float(obj[1] ),
float(obj[2] ),
float(obj[3] ),
float(obj[4] ),
] )
if not boxes:
continue
img_paths.append(snake_case__ )
labels.append(snake_case__ )
return img_paths, labels
def UpperCamelCase ( snake_case__ : list ,snake_case__ : list ,snake_case__ : int = 1 ):
'''simple docstring'''
__snake_case :Dict = []
__snake_case :Any = []
__snake_case :int = []
for idx in range(len(snake_case__ ) ):
__snake_case :Optional[int] = []
__snake_case :List[str] = img_list[idx]
path_list.append(snake_case__ )
__snake_case :Union[str, Any] = anno_list[idx]
__snake_case :List[Any] = cva.imread(snake_case__ )
if flip_type == 1:
__snake_case :Optional[Any] = cva.flip(snake_case__ ,snake_case__ )
for bbox in img_annos:
__snake_case :Union[str, Any] = 1 - bbox[1]
new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] )
elif flip_type == 0:
__snake_case :Union[str, Any] = cva.flip(snake_case__ ,snake_case__ )
for bbox in img_annos:
__snake_case :Optional[Any] = 1 - bbox[2]
new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] )
new_annos_lists.append(snake_case__ )
new_imgs_list.append(snake_case__ )
return new_imgs_list, new_annos_lists, path_list
def UpperCamelCase ( snake_case__ : int = 32 ):
'''simple docstring'''
assert number_char > 1, "The number of character should greater than 1"
__snake_case :Optional[Any] = ascii_lowercase + digits
return "".join(random.choice(snake_case__ ) for _ in range(snake_case__ ) )
if __name__ == "__main__":
main()
print("""DONE ✅""")
| 291 | 0 |
"""simple docstring"""
import os
def __UpperCAmelCase ( ):
"""simple docstring"""
with open(os.path.dirname(lowerCAmelCase__ ) + """/p022_names.txt""" ) as file:
_UpperCAmelCase = str(file.readlines()[0] )
_UpperCAmelCase = names.replace("""\"""" ,"""""" ).split(""",""" )
names.sort()
_UpperCAmelCase = 0
_UpperCAmelCase = 0
for i, name in enumerate(lowerCAmelCase__ ):
for letter in name:
name_score += ord(lowerCAmelCase__ ) - 64
total_score += (i + 1) * name_score
_UpperCAmelCase = 0
return total_score
if __name__ == "__main__":
print(solution())
| 277 |
"""simple docstring"""
import math
from enum import Enum
from typing import Optional, Union
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR
from .utils import logging
SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__)
class snake_case_ ( _lowerCamelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_: Optional[Any] = """linear"""
SCREAMING_SNAKE_CASE_: Dict = """cosine"""
SCREAMING_SNAKE_CASE_: Tuple = """cosine_with_restarts"""
SCREAMING_SNAKE_CASE_: Dict = """polynomial"""
SCREAMING_SNAKE_CASE_: Optional[int] = """constant"""
SCREAMING_SNAKE_CASE_: str = """constant_with_warmup"""
SCREAMING_SNAKE_CASE_: Optional[int] = """piecewise_constant"""
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ = -1 ):
return LambdaLR(lowerCAmelCase__ ,lambda lowerCAmelCase__ : 1 ,last_epoch=lowerCAmelCase__ )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = -1 ):
def lr_lambda(lowerCAmelCase__ ):
if current_step < num_warmup_steps:
return float(lowerCAmelCase__ ) / float(max(1.0 ,lowerCAmelCase__ ) )
return 1.0
return LambdaLR(lowerCAmelCase__ ,lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = -1 ):
A__ = {}
A__ = step_rules.split(',' )
for rule_str in rule_list[:-1]:
A__ , A__ = rule_str.split(':' )
A__ = int(lowerCAmelCase__ )
A__ = float(lowerCAmelCase__ )
A__ = value
A__ = float(rule_list[-1] )
def create_rules_function(lowerCAmelCase__ ,lowerCAmelCase__ ):
def rule_func(lowerCAmelCase__ ) -> float:
A__ = sorted(rules_dict.keys() )
for i, sorted_step in enumerate(lowerCAmelCase__ ):
if steps < sorted_step:
return rules_dict[sorted_steps[i]]
return last_lr_multiple
return rule_func
A__ = create_rules_function(lowerCAmelCase__ ,lowerCAmelCase__ )
return LambdaLR(lowerCAmelCase__ ,lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=-1 ):
def lr_lambda(lowerCAmelCase__ ):
if current_step < num_warmup_steps:
return float(lowerCAmelCase__ ) / float(max(1 ,lowerCAmelCase__ ) )
return max(
0.0 ,float(num_training_steps - current_step ) / float(max(1 ,num_training_steps - num_warmup_steps ) ) )
return LambdaLR(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 0.5 ,lowerCAmelCase__ = -1 ):
def lr_lambda(lowerCAmelCase__ ):
if current_step < num_warmup_steps:
return float(lowerCAmelCase__ ) / float(max(1 ,lowerCAmelCase__ ) )
A__ = float(current_step - num_warmup_steps ) / float(max(1 ,num_training_steps - num_warmup_steps ) )
return max(0.0 ,0.5 * (1.0 + math.cos(math.pi * float(lowerCAmelCase__ ) * 2.0 * progress )) )
return LambdaLR(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 1 ,lowerCAmelCase__ = -1 ):
def lr_lambda(lowerCAmelCase__ ):
if current_step < num_warmup_steps:
return float(lowerCAmelCase__ ) / float(max(1 ,lowerCAmelCase__ ) )
A__ = float(current_step - num_warmup_steps ) / float(max(1 ,num_training_steps - num_warmup_steps ) )
if progress >= 1.0:
return 0.0
return max(0.0 ,0.5 * (1.0 + math.cos(math.pi * ((float(lowerCAmelCase__ ) * progress) % 1.0) )) )
return LambdaLR(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=1E-7 ,lowerCAmelCase__=1.0 ,lowerCAmelCase__=-1 ):
A__ = optimizer.defaults['lr']
if not (lr_init > lr_end):
raise ValueError(f'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' )
def lr_lambda(lowerCAmelCase__ ):
if current_step < num_warmup_steps:
return float(lowerCAmelCase__ ) / float(max(1 ,lowerCAmelCase__ ) )
elif current_step > num_training_steps:
return lr_end / lr_init # as LambdaLR multiplies by lr_init
else:
A__ = lr_init - lr_end
A__ = num_training_steps - num_warmup_steps
A__ = 1 - (current_step - num_warmup_steps) / decay_steps
A__ = lr_range * pct_remaining**power + lr_end
return decay / lr_init # as LambdaLR multiplies by lr_init
return LambdaLR(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[Any] = {
SchedulerType.LINEAR: get_linear_schedule_with_warmup,
SchedulerType.COSINE: get_cosine_schedule_with_warmup,
SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup,
SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup,
SchedulerType.CONSTANT: get_constant_schedule,
SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup,
SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule,
}
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = None ,lowerCAmelCase__ = None ,lowerCAmelCase__ = None ,lowerCAmelCase__ = 1 ,lowerCAmelCase__ = 1.0 ,lowerCAmelCase__ = -1 ,):
A__ = SchedulerType(lowerCAmelCase__ )
A__ = TYPE_TO_SCHEDULER_FUNCTION[name]
if name == SchedulerType.CONSTANT:
return schedule_func(lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ )
if name == SchedulerType.PIECEWISE_CONSTANT:
return schedule_func(lowerCAmelCase__ ,step_rules=lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ )
# All other schedulers require `num_warmup_steps`
if num_warmup_steps is None:
raise ValueError(f'''{name} requires `num_warmup_steps`, please provide that argument.''' )
if name == SchedulerType.CONSTANT_WITH_WARMUP:
return schedule_func(lowerCAmelCase__ ,num_warmup_steps=lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ )
# All other schedulers require `num_training_steps`
if num_training_steps is None:
raise ValueError(f'''{name} requires `num_training_steps`, please provide that argument.''' )
if name == SchedulerType.COSINE_WITH_RESTARTS:
return schedule_func(
lowerCAmelCase__ ,num_warmup_steps=lowerCAmelCase__ ,num_training_steps=lowerCAmelCase__ ,num_cycles=lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ ,)
if name == SchedulerType.POLYNOMIAL:
return schedule_func(
lowerCAmelCase__ ,num_warmup_steps=lowerCAmelCase__ ,num_training_steps=lowerCAmelCase__ ,power=lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ ,)
return schedule_func(
lowerCAmelCase__ ,num_warmup_steps=lowerCAmelCase__ ,num_training_steps=lowerCAmelCase__ ,last_epoch=lowerCAmelCase__ )
| 260 | 0 |
import json
import os
import unittest
from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class _lowerCAmelCase ( _lowercase , unittest.TestCase ):
A__ = DebertaTokenizer
A__ = True
A__ = DebertaTokenizerFast
def __magic_name__( self ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCAmelCase__ : Optional[Any] = [
'''l''',
'''o''',
'''w''',
'''e''',
'''r''',
'''s''',
'''t''',
'''i''',
'''d''',
'''n''',
'''\u0120''',
'''\u0120l''',
'''\u0120n''',
'''\u0120lo''',
'''\u0120low''',
'''er''',
'''\u0120lowest''',
'''\u0120newer''',
'''\u0120wider''',
'''[UNK]''',
]
lowerCAmelCase__ : Dict = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) )
lowerCAmelCase__ : str = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
lowerCAmelCase__ : str = {'''unk_token''': '''[UNK]'''}
lowerCAmelCase__ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
lowerCAmelCase__ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(__UpperCAmelCase ) + '''\n''' )
with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write('''\n'''.join(__UpperCAmelCase ) )
def __magic_name__( self , **__UpperCAmelCase ):
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase )
def __magic_name__( self , __UpperCAmelCase ):
lowerCAmelCase__ : Any = '''lower newer'''
lowerCAmelCase__ : Optional[Any] = '''lower newer'''
return input_text, output_text
def __magic_name__( self ):
lowerCAmelCase__ : int = self.get_tokenizer()
lowerCAmelCase__ : Union[str, Any] = '''lower newer'''
lowerCAmelCase__ : Any = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
lowerCAmelCase__ : Optional[Any] = tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
lowerCAmelCase__ : str = tokens + [tokenizer.unk_token]
lowerCAmelCase__ : int = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , __UpperCAmelCase )
def __magic_name__( self ):
lowerCAmelCase__ : List[str] = self.get_tokenizer()
lowerCAmelCase__ : Optional[int] = tokenizer('''Hello''' , '''World''' )
lowerCAmelCase__ : List[Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
self.assertListEqual(tokd['''token_type_ids'''] , __UpperCAmelCase )
@slow
def __magic_name__( self ):
lowerCAmelCase__ : Any = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' )
lowerCAmelCase__ : Union[str, Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__UpperCAmelCase )
lowerCAmelCase__ : Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__UpperCAmelCase )
lowerCAmelCase__ : Tuple = tokenizer.encode(
'''sequence builders''' , add_special_tokens=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase )
lowerCAmelCase__ : List[str] = tokenizer.encode(
'''sequence builders''' , '''multi-sequence build''' , add_special_tokens=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase )
lowerCAmelCase__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase )
lowerCAmelCase__ : Dict = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
@slow
def __magic_name__( self ):
lowerCAmelCase__ : List[str] = [self.tokenizer_class]
if self.test_rust_tokenizer:
tokenizer_classes.append(self.rust_tokenizer_class )
for tokenizer_class in tokenizer_classes:
lowerCAmelCase__ : List[str] = tokenizer_class.from_pretrained('''microsoft/deberta-base''' )
lowerCAmelCase__ : Union[str, Any] = [
'''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''',
'''ALBERT incorporates two parameter reduction techniques''',
'''The first one is a factorized embedding parameterization. By decomposing the large vocabulary'''
''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'''
''' vocabulary embedding.''',
]
lowerCAmelCase__ : int = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase )
lowerCAmelCase__ : Tuple = [tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) for seq in encoding['''input_ids''']]
# fmt: off
lowerCAmelCase__ : List[str] = {
'''input_ids''': [
[1, 2118, 1_1126, 565, 35, 83, 2_5191, 163, 1_8854, 13, 1_2156, 12, 1_6101, 2_5376, 1_3807, 9, 2_2205, 2_7893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 2118, 1_1126, 565, 2_4536, 80, 4_3797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 133, 78, 65, 16, 10, 3724, 1538, 3_3183, 1_1303, 4_3797, 1938, 4, 870, 2_4165, 2_9105, 5, 739, 3_2644, 3_3183, 1_1303, 3_6173, 88, 80, 650, 7821, 4_5940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 1_3171, 31, 5, 1836, 9, 3_2644, 3_3183, 1_1303, 4, 2]
],
'''token_type_ids''': [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
],
'''attention_mask''': [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
}
# fmt: on
lowerCAmelCase__ : Optional[Any] = [
'''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''',
'''ALBERT incorporates two parameter reduction techniques''',
'''The first one is a factorized embedding parameterization. By decomposing the large vocabulary'''
''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'''
''' vocabulary embedding.''',
]
self.assertDictEqual(encoding.data , __UpperCAmelCase )
for expected, decoded in zip(__UpperCAmelCase , __UpperCAmelCase ):
self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
| 470 |
import baseaa
import io
import json
import os
from copy import deepcopy
from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler
class _lowerCAmelCase :
def __init__( self , __UpperCAmelCase ):
if isinstance(__UpperCAmelCase , __UpperCAmelCase ):
# Don't modify user's data should they want to reuse it (e.g. in tests), because once we
# modified it, it will not be accepted here again, since `auto` values would have been overridden
lowerCAmelCase__ : Union[str, Any] = deepcopy(__UpperCAmelCase )
elif os.path.exists(__UpperCAmelCase ):
with io.open(__UpperCAmelCase , '''r''' , encoding='''utf-8''' ) as f:
lowerCAmelCase__ : int = json.load(__UpperCAmelCase )
else:
try:
lowerCAmelCase__ : Union[str, Any] = baseaa.urlsafe_baadecode(__UpperCAmelCase ).decode('''utf-8''' )
lowerCAmelCase__ : Optional[int] = json.loads(__UpperCAmelCase )
except (UnicodeDecodeError, AttributeError, ValueError):
raise ValueError(
f"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" )
lowerCAmelCase__ : Optional[Any] = config
self.set_stage_and_offload()
def __magic_name__( self ):
# zero stage - this is done as early as possible, before model is created, to allow
# ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object
# during ``zero.Init()`` which needs to know the dtype, and some other hparams.
lowerCAmelCase__ : Optional[Any] = self.get_value('''zero_optimization.stage''' , -1 )
# offload
lowerCAmelCase__ : Dict = False
if self.is_zeroa() or self.is_zeroa():
lowerCAmelCase__ : Dict = set(['''cpu''', '''nvme'''] )
lowerCAmelCase__ : Optional[Any] = set(
[
self.get_value('''zero_optimization.offload_optimizer.device''' ),
self.get_value('''zero_optimization.offload_param.device''' ),
] )
if len(offload_devices & offload_devices_valid ) > 0:
lowerCAmelCase__ : List[Any] = True
def __magic_name__( self , __UpperCAmelCase ):
lowerCAmelCase__ : int = self.config
# find the config node of interest if it exists
lowerCAmelCase__ : Tuple = ds_key_long.split('''.''' )
lowerCAmelCase__ : int = nodes.pop()
for node in nodes:
lowerCAmelCase__ : int = config.get(__UpperCAmelCase )
if config is None:
return None, ds_key
return config, ds_key
def __magic_name__( self , __UpperCAmelCase , __UpperCAmelCase=None ):
lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = self.find_config_node(__UpperCAmelCase )
if config is None:
return default
return config.get(__UpperCAmelCase , __UpperCAmelCase )
def __magic_name__( self , __UpperCAmelCase , __UpperCAmelCase=False ):
lowerCAmelCase__ : Dict = self.config
# find the config node of interest if it exists
lowerCAmelCase__ : str = ds_key_long.split('''.''' )
for node in nodes:
lowerCAmelCase__ : Dict = config
lowerCAmelCase__ : List[str] = config.get(__UpperCAmelCase )
if config is None:
if must_exist:
raise ValueError(f"""Can't find {ds_key_long} entry in the config: {self.config}""" )
else:
return
# if found remove it
if parent_config is not None:
parent_config.pop(__UpperCAmelCase )
def __magic_name__( self , __UpperCAmelCase ):
lowerCAmelCase__ : Union[str, Any] = self.get_value(__UpperCAmelCase )
return False if value is None else bool(__UpperCAmelCase )
def __magic_name__( self , __UpperCAmelCase ):
lowerCAmelCase__ : Optional[Any] = self.get_value(__UpperCAmelCase )
return False if value is None else not bool(__UpperCAmelCase )
def __magic_name__( self ):
return self._stage == 2
def __magic_name__( self ):
return self._stage == 3
def __magic_name__( self ):
return self._offload
class _lowerCAmelCase :
def __init__( self , __UpperCAmelCase ):
lowerCAmelCase__ : int = engine
def __magic_name__( self , __UpperCAmelCase , **__UpperCAmelCase ):
# runs backpropagation and handles mixed precision
self.engine.backward(__UpperCAmelCase , **__UpperCAmelCase )
# Deepspeed's `engine.step` performs the following operations:
# - gradient accumulation check
# - gradient clipping
# - optimizer step
# - zero grad
# - checking overflow
# - lr_scheduler step (only if engine.lr_scheduler is not None)
self.engine.step()
# and this plugin overrides the above calls with no-ops when Accelerate runs under
# Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
# training loop that works transparently under many training regimes.
class _lowerCAmelCase ( _lowercase ):
def __init__( self , __UpperCAmelCase ):
super().__init__(__UpperCAmelCase , device_placement=__UpperCAmelCase , scaler=__UpperCAmelCase )
lowerCAmelCase__ : Optional[int] = hasattr(self.optimizer , '''overflow''' )
def __magic_name__( self , __UpperCAmelCase=None ):
pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
def __magic_name__( self ):
pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
@property
def __magic_name__( self ):
if self.__has_overflow__:
return self.optimizer.overflow
return False
class _lowerCAmelCase ( _lowercase ):
def __init__( self , __UpperCAmelCase , __UpperCAmelCase ):
super().__init__(__UpperCAmelCase , __UpperCAmelCase )
def __magic_name__( self ):
pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
class _lowerCAmelCase :
def __init__( self , __UpperCAmelCase , __UpperCAmelCase=0.001 , __UpperCAmelCase=0 , **__UpperCAmelCase ):
lowerCAmelCase__ : Any = params
lowerCAmelCase__ : str = lr
lowerCAmelCase__ : List[str] = weight_decay
lowerCAmelCase__ : Dict = kwargs
class _lowerCAmelCase :
def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=0 , **__UpperCAmelCase ):
lowerCAmelCase__ : Union[str, Any] = optimizer
lowerCAmelCase__ : Optional[Any] = total_num_steps
lowerCAmelCase__ : str = warmup_num_steps
lowerCAmelCase__ : Dict = kwargs
| 470 | 1 |
"""simple docstring"""
import os
import unittest
from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCamelCase_ (__A , unittest.TestCase ):
__magic_name__ = FunnelTokenizer
__magic_name__ = FunnelTokenizerFast
__magic_name__ = True
__magic_name__ = True
def _SCREAMING_SNAKE_CASE ( self : str ) -> str:
super().setUp()
UpperCAmelCase_ : Optional[int] = [
"<unk>",
"<cls>",
"<sep>",
"want",
"##want",
"##ed",
"wa",
"un",
"runn",
"##ing",
",",
"low",
"lowest",
]
UpperCAmelCase_ : List[Any] = 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 _SCREAMING_SNAKE_CASE ( self : Dict , **lowerCAmelCase_ : List[Any] ) -> Any:
return FunnelTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : int , **lowerCAmelCase_ : Any ) -> Dict:
return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : str ) -> Dict:
UpperCAmelCase_ : Union[str, Any] = "UNwant\u00E9d,running"
UpperCAmelCase_ : Optional[Any] = "unwanted, running"
return input_text, output_text
def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]:
UpperCAmelCase_ : str = self.tokenizer_class(self.vocab_file )
UpperCAmelCase_ : List[str] = tokenizer.tokenize("UNwant\u00E9d,running" )
self.assertListEqual(lowerCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) , [7, 4, 5, 10, 8, 9] )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple:
UpperCAmelCase_ : List[Any] = self.get_tokenizers(do_lower_case=lowerCAmelCase_ )
for tokenizer in tokenizers:
UpperCAmelCase_ : Union[str, Any] = tokenizer("UNwant\u00E9d,running" )
UpperCAmelCase_ : List[Any] = len(inputs["input_ids"] ) - 1
self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len )
UpperCAmelCase_ : Union[str, Any] = tokenizer("UNwant\u00E9d,running" , "UNwant\u00E9d,running" )
self.assertListEqual(inputs["token_type_ids"] , [2] + [0] * sentence_len + [1] * sentence_len )
| 95 |
"""simple docstring"""
def _lowerCamelCase ( lowerCamelCase__ : str ):
assert column_title.isupper()
lowercase__ : int = 0
lowercase__ : Optional[int] = len(lowerCamelCase__ ) - 1
lowercase__ : int = 0
while index >= 0:
lowercase__ : List[str] = (ord(column_title[index] ) - 64) * pow(26 , lowerCamelCase__ )
answer += value
power += 1
index -= 1
return answer
if __name__ == "__main__":
from doctest import testmod
testmod() | 200 | 0 |
from __future__ import annotations
import unittest
from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers.models.xglm.modeling_tf_xglm import (
TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXGLMForCausalLM,
TFXGLMModel,
)
@require_tf
class __snake_case :
__lowerCamelCase = XGLMConfig
__lowerCamelCase = {}
__lowerCamelCase = """gelu"""
def __init__( self , __UpperCamelCase , __UpperCamelCase=14 , __UpperCamelCase=7 , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=99 , __UpperCamelCase=32 , __UpperCamelCase=2 , __UpperCamelCase=4 , __UpperCamelCase=37 , __UpperCamelCase="gelu" , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=512 , __UpperCamelCase=0.0_2 , ) -> List[Any]:
'''simple docstring'''
snake_case__ : List[str] = parent
snake_case__ : List[Any] = batch_size
snake_case__ : Any = seq_length
snake_case__ : Union[str, Any] = is_training
snake_case__ : Optional[int] = use_input_mask
snake_case__ : Any = use_labels
snake_case__ : List[str] = vocab_size
snake_case__ : Tuple = d_model
snake_case__ : List[Any] = num_hidden_layers
snake_case__ : Dict = num_attention_heads
snake_case__ : Dict = ffn_dim
snake_case__ : Optional[Any] = activation_function
snake_case__ : Any = activation_dropout
snake_case__ : Tuple = attention_dropout
snake_case__ : Union[str, Any] = max_position_embeddings
snake_case__ : List[Any] = initializer_range
snake_case__ : str = None
snake_case__ : Union[str, Any] = 0
snake_case__ : str = 2
snake_case__ : Any = 1
def __a ( self ) -> Optional[int]:
'''simple docstring'''
return XGLMConfig.from_pretrained('facebook/xglm-564M' )
def __a ( self ) -> Any:
'''simple docstring'''
snake_case__ : Any = tf.clip_by_value(
ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 )
snake_case__ : Optional[Any] = None
if self.use_input_mask:
snake_case__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] )
snake_case__ : str = self.get_config()
snake_case__ : int = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
input_mask,
head_mask,
)
def __a ( self ) -> Dict:
'''simple docstring'''
return XGLMConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=__UpperCamelCase , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=__UpperCamelCase , )
def __a ( self ) -> Optional[int]:
'''simple docstring'''
snake_case__ : List[str] = self.prepare_config_and_inputs()
(
(
snake_case__
) , (
snake_case__
) , (
snake_case__
) , (
snake_case__
) ,
) : int = config_and_inputs
snake_case__ : Any = {
'input_ids': input_ids,
'head_mask': head_mask,
}
return config, inputs_dict
@require_tf
class __snake_case ( _lowerCamelCase ,_lowerCamelCase ,unittest.TestCase ):
__lowerCamelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
__lowerCamelCase = (TFXGLMForCausalLM,) if is_tf_available() else ()
__lowerCamelCase = (
{"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {}
)
__lowerCamelCase = False
__lowerCamelCase = False
__lowerCamelCase = False
def __a ( self ) -> int:
'''simple docstring'''
snake_case__ : List[Any] = TFXGLMModelTester(self )
snake_case__ : int = ConfigTester(self , config_class=__UpperCamelCase , n_embd=37 )
def __a ( self ) -> Any:
'''simple docstring'''
self.config_tester.run_common_tests()
@slow
def __a ( self ) -> List[Any]:
'''simple docstring'''
for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case__ : str = TFXGLMModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
@unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' )
def __a ( self ) -> Union[str, Any]:
'''simple docstring'''
super().test_resize_token_embeddings()
@require_tf
class __snake_case ( unittest.TestCase ):
@slow
def __a ( self , __UpperCamelCase=True ) -> List[Any]:
'''simple docstring'''
snake_case__ : Union[str, Any] = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
snake_case__ : Optional[int] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog
# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
# fmt: off
snake_case__ : str = [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581]
# fmt: on
snake_case__ : int = model.generate(__UpperCamelCase , do_sample=__UpperCamelCase , num_beams=1 )
if verify_outputs:
self.assertListEqual(output_ids[0].numpy().tolist() , __UpperCamelCase )
@slow
def __a ( self ) -> List[str]:
'''simple docstring'''
snake_case__ : List[Any] = XGLMTokenizer.from_pretrained('facebook/xglm-564M' )
snake_case__ : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
tf.random.set_seed(0 )
snake_case__ : Any = tokenizer('Today is a nice day and' , return_tensors='tf' )
snake_case__ : List[str] = tokenized.input_ids
# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
with tf.device(':/CPU:0' ):
snake_case__ : Any = model.generate(__UpperCamelCase , do_sample=__UpperCamelCase , seed=[7, 0] )
snake_case__ : List[str] = tokenizer.decode(output_ids[0] , skip_special_tokens=__UpperCamelCase )
snake_case__ : Union[str, Any] = (
'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'
)
self.assertEqual(__UpperCamelCase , __UpperCamelCase )
@slow
def __a ( self ) -> Optional[Any]:
'''simple docstring'''
snake_case__ : int = TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
snake_case__ : List[str] = XGLMTokenizer.from_pretrained('facebook/xglm-564M' )
snake_case__ : str = 'left'
# use different length sentences to test batching
snake_case__ : Tuple = [
'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
'left-padding, such as in batched generation. The output for the sequence below should be the same '
'regardless of whether left padding is applied or not. When',
'Hello, my dog is a little',
]
snake_case__ : Optional[Any] = tokenizer(__UpperCamelCase , return_tensors='tf' , padding=__UpperCamelCase )
snake_case__ : str = inputs['input_ids']
snake_case__ : List[Any] = model.generate(input_ids=__UpperCamelCase , attention_mask=inputs['attention_mask'] , max_new_tokens=12 )
snake_case__ : Dict = tokenizer(sentences[0] , return_tensors='tf' ).input_ids
snake_case__ : Tuple = model.generate(input_ids=__UpperCamelCase , max_new_tokens=12 )
snake_case__ : List[Any] = tokenizer(sentences[1] , return_tensors='tf' ).input_ids
snake_case__ : Optional[Any] = model.generate(input_ids=__UpperCamelCase , max_new_tokens=12 )
snake_case__ : Optional[int] = tokenizer.batch_decode(__UpperCamelCase , skip_special_tokens=__UpperCamelCase )
snake_case__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__UpperCamelCase )
snake_case__ : Dict = tokenizer.decode(output_padded[0] , skip_special_tokens=__UpperCamelCase )
snake_case__ : int = [
'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
'left-padding, such as in batched generation. The output for the sequence below should be the same '
'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '
'a single',
'Hello, my dog is a little bit of a shy one, but he is very friendly',
]
self.assertListEqual(__UpperCamelCase , __UpperCamelCase )
self.assertListEqual(__UpperCamelCase , [non_padded_sentence, padded_sentence] )
| 699 | def UpperCamelCase__ ( A__ , A__ , A__ ) -> int:
if exponent == 1:
return base
if exponent % 2 == 0:
snake_case__ : Dict = _modexpt(A__ , exponent // 2 , A__ ) % modulo_value
return (x * x) % modulo_value
else:
return (base * _modexpt(A__ , exponent - 1 , A__ )) % modulo_value
def UpperCamelCase__ ( A__ = 1777 , A__ = 1855 , A__ = 8 ) -> int:
snake_case__ : Tuple = base
for _ in range(1 , A__ ):
snake_case__ : Any = _modexpt(A__ , A__ , 10**digits )
return result
if __name__ == "__main__":
print(F'''{solution() = }''')
| 699 | 1 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase =logging.get_logger(__name__)
lowercase ={
'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json',
}
class __magic_name__ ( lowerCAmelCase ):
UpperCAmelCase ="git_vision_model"
def __init__( self , snake_case=7_6_8 , snake_case=3_0_7_2 , snake_case=1_2 , snake_case=1_2 , snake_case=3 , snake_case=2_2_4 , snake_case=1_6 , snake_case="quick_gelu" , snake_case=1E-5 , snake_case=0.0 , snake_case=0.02 , **snake_case , ) -> str:
'''simple docstring'''
super().__init__(**snake_case)
_UpperCAmelCase : Any =hidden_size
_UpperCAmelCase : Optional[int] =intermediate_size
_UpperCAmelCase : Dict =num_hidden_layers
_UpperCAmelCase : Optional[Any] =num_attention_heads
_UpperCAmelCase : Dict =num_channels
_UpperCAmelCase : Optional[Any] =patch_size
_UpperCAmelCase : Tuple =image_size
_UpperCAmelCase : int =initializer_range
_UpperCAmelCase : Any =attention_dropout
_UpperCAmelCase : str =layer_norm_eps
_UpperCAmelCase : Union[str, Any] =hidden_act
@classmethod
def lowerCAmelCase ( cls , snake_case , **snake_case) -> "PretrainedConfig":
'''simple docstring'''
cls._set_token_in_kwargs(snake_case)
_UpperCAmelCase , _UpperCAmelCase : Tuple =cls.get_config_dict(snake_case , **snake_case)
# get the vision config dict if we are loading from GITConfig
if config_dict.get('model_type') == "git":
_UpperCAmelCase : List[str] =config_dict['vision_config']
if "model_type" in config_dict and hasattr(cls , 'model_type') and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
return cls.from_dict(snake_case , **snake_case)
class __magic_name__ ( lowerCAmelCase ):
UpperCAmelCase ="git"
def __init__( self , snake_case=None , snake_case=3_0_5_2_2 , snake_case=7_6_8 , snake_case=6 , snake_case=1_2 , snake_case=3_0_7_2 , snake_case="gelu" , snake_case=0.1 , snake_case=0.1 , snake_case=1_0_2_4 , snake_case=0.02 , snake_case=1E-1_2 , snake_case=0 , snake_case="absolute" , snake_case=True , snake_case=False , snake_case=1_0_1 , snake_case=1_0_2 , snake_case=None , **snake_case , ) -> Tuple:
'''simple docstring'''
super().__init__(bos_token_id=snake_case , eos_token_id=snake_case , pad_token_id=snake_case , **snake_case)
if vision_config is None:
_UpperCAmelCase : Union[str, Any] ={}
logger.info('vision_config is None. initializing the GitVisionConfig with default values.')
_UpperCAmelCase : Tuple =GitVisionConfig(**snake_case)
_UpperCAmelCase : Optional[int] =vocab_size
_UpperCAmelCase : str =hidden_size
_UpperCAmelCase : List[Any] =num_hidden_layers
_UpperCAmelCase : Optional[Any] =num_attention_heads
_UpperCAmelCase : int =hidden_act
_UpperCAmelCase : List[Any] =intermediate_size
_UpperCAmelCase : str =hidden_dropout_prob
_UpperCAmelCase : Union[str, Any] =attention_probs_dropout_prob
_UpperCAmelCase : Dict =max_position_embeddings
_UpperCAmelCase : str =initializer_range
_UpperCAmelCase : Optional[Any] =layer_norm_eps
_UpperCAmelCase : str =position_embedding_type
_UpperCAmelCase : Optional[Any] =use_cache
_UpperCAmelCase : Any =tie_word_embeddings
_UpperCAmelCase : Union[str, Any] =num_image_with_embedding
_UpperCAmelCase : int =bos_token_id
_UpperCAmelCase : List[str] =eos_token_id
def lowerCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCAmelCase : str =copy.deepcopy(self.__dict__)
_UpperCAmelCase : Any =self.vision_config.to_dict()
_UpperCAmelCase : str =self.__class__.model_type
return output
| 446 |
'''simple docstring'''
import inspect
import re
from hashlib import shaaaa
from typing import Dict, List
from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql # noqa F401
from .text import text
def lowerCamelCase__ ( __lowerCamelCase : List[str] ):
'''simple docstring'''
_UpperCAmelCase : int =[]
for line in lines:
_UpperCAmelCase : Dict =re.sub(R'#.*' , '' , __lowerCamelCase ) # remove comments
if line:
filtered_lines.append(__lowerCamelCase )
_UpperCAmelCase : str ='\n'.join(__lowerCamelCase )
# Make a hash from all this code
_UpperCAmelCase : str =full_str.encode('utf-8' )
return shaaaa(__lowerCamelCase ).hexdigest()
# get importable module names and hash for caching
lowercase ={
'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}
# Used to infer the module to use based on the data files extensions
lowercase ={
'.csv': ('csv', {}),
'.tsv': ('csv', {'sep': '\t'}),
'.json': ('json', {}),
'.jsonl': ('json', {}),
'.parquet': ('parquet', {}),
'.arrow': ('arrow', {}),
'.txt': ('text', {}),
}
_EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
lowercase ={'imagefolder', 'audiofolder'}
# Used to filter data files based on extensions given a module name
lowercase ={}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
_MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)
_MODULE_TO_EXTENSIONS["imagefolder"].append('.zip')
_MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
| 446 | 1 |
"""simple docstring"""
import unittest
from transformers import SPIECE_UNDERLINE
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.tokenization_utils import AddedToken
from ...test_tokenization_common import TokenizerTesterMixin
lowercase__ : Tuple = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''')
@require_sentencepiece
@require_tokenizers
class _UpperCAmelCase ( __snake_case , unittest.TestCase):
_lowerCAmelCase : Optional[Any] = SpeechTaTokenizer
_lowerCAmelCase : Union[str, Any] = False
_lowerCAmelCase : List[Any] = True
def _snake_case ( self : Any ):
super().setUp()
# We have a SentencePiece fixture for testing
snake_case_ : int = SpeechTaTokenizer(__UpperCamelCase )
snake_case_ : int = AddedToken('''<mask>''' , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase )
snake_case_ : Any = mask_token
tokenizer.add_special_tokens({'''mask_token''': mask_token} )
tokenizer.add_tokens(['''<ctc_blank>'''] )
tokenizer.save_pretrained(self.tmpdirname )
def _snake_case ( self : List[str] , lowercase_ : Any ):
snake_case_ : List[str] = '''this is a test'''
snake_case_ : str = '''this is a test'''
return input_text, output_text
def _snake_case ( self : str , lowercase_ : Tuple , lowercase_ : Dict=False , lowercase_ : Union[str, Any]=20 , lowercase_ : Any=5 ):
snake_case_, snake_case_ : Dict = self.get_input_output_texts(__UpperCamelCase )
snake_case_ : List[Any] = tokenizer.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase )
snake_case_ : Union[str, Any] = tokenizer.decode(__UpperCamelCase , clean_up_tokenization_spaces=__UpperCamelCase )
return text, ids
def _snake_case ( self : Optional[int] ):
snake_case_ : Dict = '''<pad>'''
snake_case_ : int = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCamelCase ) , __UpperCamelCase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCamelCase ) , __UpperCamelCase )
def _snake_case ( self : Optional[int] ):
snake_case_ : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''<s>''' )
self.assertEqual(vocab_keys[1] , '''<pad>''' )
self.assertEqual(vocab_keys[-4] , '''œ''' )
self.assertEqual(vocab_keys[-2] , '''<mask>''' )
self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' )
self.assertEqual(len(__UpperCamelCase ) , 81 )
def _snake_case ( self : Union[str, Any] ):
self.assertEqual(self.get_tokenizer().vocab_size , 79 )
def _snake_case ( self : str ):
snake_case_ : List[Any] = self.get_tokenizers(do_lower_case=__UpperCamelCase )
for tokenizer in tokenizers:
with self.subTest(f"{tokenizer.__class__.__name__}" ):
snake_case_ : List[str] = tokenizer.vocab_size
snake_case_ : Dict = len(__UpperCamelCase )
self.assertNotEqual(__UpperCamelCase , 0 )
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
snake_case_ : Any = ['''aaaaa bbbbbb''', '''cccccccccdddddddd''']
snake_case_ : Tuple = tokenizer.add_tokens(__UpperCamelCase )
snake_case_ : int = tokenizer.vocab_size
snake_case_ : str = len(__UpperCamelCase )
self.assertNotEqual(__UpperCamelCase , 0 )
self.assertEqual(__UpperCamelCase , __UpperCamelCase )
self.assertEqual(__UpperCamelCase , len(__UpperCamelCase ) )
self.assertEqual(__UpperCamelCase , all_size + len(__UpperCamelCase ) )
snake_case_ : Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__UpperCamelCase )
self.assertGreaterEqual(len(__UpperCamelCase ) , 4 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
snake_case_ : Any = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''}
snake_case_ : Dict = tokenizer.add_special_tokens(__UpperCamelCase )
snake_case_ : str = tokenizer.vocab_size
snake_case_ : Dict = len(__UpperCamelCase )
self.assertNotEqual(__UpperCamelCase , 0 )
self.assertEqual(__UpperCamelCase , __UpperCamelCase )
self.assertEqual(__UpperCamelCase , len(__UpperCamelCase ) )
self.assertEqual(__UpperCamelCase , all_size_a + len(__UpperCamelCase ) )
snake_case_ : int = tokenizer.encode(
'''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__UpperCamelCase )
self.assertGreaterEqual(len(__UpperCamelCase ) , 6 )
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[0] , tokens[1] )
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 )
self.assertGreater(tokens[-3] , tokens[-4] )
self.assertEqual(tokens[0] , tokenizer.eos_token_id )
self.assertEqual(tokens[-3] , tokenizer.pad_token_id )
def _snake_case ( self : str ):
pass
def _snake_case ( self : Any ):
pass
def _snake_case ( self : List[Any] ):
snake_case_ : Optional[int] = self.get_tokenizer()
snake_case_ : Tuple = tokenizer.tokenize('''This is a test''' )
# fmt: off
self.assertListEqual(__UpperCamelCase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] )
# fmt: on
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__UpperCamelCase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , )
snake_case_ : str = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' )
self.assertListEqual(
__UpperCamelCase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] )
snake_case_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__UpperCamelCase )
# fmt: off
self.assertListEqual(__UpperCamelCase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] )
# fmt: on
snake_case_ : Dict = tokenizer.convert_ids_to_tokens(__UpperCamelCase )
self.assertListEqual(
__UpperCamelCase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] )
@slow
def _snake_case ( self : Dict ):
snake_case_ : Optional[Any] = [
'''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides '''
'''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural '''
'''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained '''
'''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''',
'''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly '''
'''conditioning on both left and right context in all layers.''',
'''The quick brown fox jumps over the lazy dog.''',
]
# fmt: off
snake_case_ : Union[str, Any] = {
'''input_ids''': [
[4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2],
[4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
],
'''attention_mask''': [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__UpperCamelCase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__UpperCamelCase , )
| 702 |
"""simple docstring"""
def __lowercase ( _a , _a ):
snake_case_ : str = [0 for i in range(r + 1 )]
# nc0 = 1
snake_case_ : int = 1
for i in range(1 , n + 1 ):
# to compute current row from previous row.
snake_case_ : Any = min(_a , _a )
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r]
print(binomial_coefficient(n=10, r=5))
| 485 | 0 |
"""simple docstring"""
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
if TYPE_CHECKING:
from ... import FeatureExtractionMixin, TensorType
__lowerCamelCase :Optional[Any] = logging.get_logger(__name__)
__lowerCamelCase :Optional[int] = {
'openai/imagegpt-small': '',
'openai/imagegpt-medium': '',
'openai/imagegpt-large': '',
}
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : Union[str, Any] ='''imagegpt'''
snake_case__ : Dict =['''past_key_values''']
snake_case__ : Dict ={
'''hidden_size''': '''n_embd''',
'''max_position_embeddings''': '''n_positions''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self: Any , __a: int=512 + 1 , __a: Dict=32 * 32 , __a: Union[str, Any]=512 , __a: List[Any]=24 , __a: Dict=8 , __a: Optional[Any]=None , __a: Union[str, Any]="quick_gelu" , __a: List[str]=0.1 , __a: List[str]=0.1 , __a: List[Any]=0.1 , __a: Any=1e-5 , __a: int=0.02 , __a: Any=True , __a: Union[str, Any]=True , __a: Any=False , __a: str=False , __a: Any=False , **__a: str , )-> List[Any]:
lowerCamelCase : int = vocab_size
lowerCamelCase : Union[str, Any] = n_positions
lowerCamelCase : Optional[int] = n_embd
lowerCamelCase : int = n_layer
lowerCamelCase : Tuple = n_head
lowerCamelCase : List[Any] = n_inner
lowerCamelCase : Optional[int] = activation_function
lowerCamelCase : str = resid_pdrop
lowerCamelCase : Any = embd_pdrop
lowerCamelCase : Any = attn_pdrop
lowerCamelCase : Any = layer_norm_epsilon
lowerCamelCase : List[str] = initializer_range
lowerCamelCase : List[Any] = scale_attn_weights
lowerCamelCase : Union[str, Any] = use_cache
lowerCamelCase : Tuple = scale_attn_by_inverse_layer_idx
lowerCamelCase : int = reorder_and_upcast_attn
lowerCamelCase : Union[str, Any] = tie_word_embeddings
super().__init__(tie_word_embeddings=__a , **__a )
class A__ ( __lowercase):
"""simple docstring"""
@property
def a__ ( self: Union[str, Any] )-> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("""input_ids""", {0: """batch""", 1: """sequence"""}),
] )
def a__ ( self: Union[str, Any] , __a: "FeatureExtractionMixin" , __a: int = 1 , __a: int = -1 , __a: bool = False , __a: Optional["TensorType"] = None , __a: int = 3 , __a: int = 32 , __a: int = 32 , )-> Mapping[str, Any]:
lowerCamelCase : str = self._generate_dummy_images(__a , __a , __a , __a )
lowerCamelCase : Optional[Any] = dict(preprocessor(images=__a , return_tensors=__a ) )
return inputs
| 222 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__lowerCamelCase :Union[str, Any] = logging.get_logger(__name__)
__lowerCamelCase :Union[str, Any] = {
'facebook/deit-base-distilled-patch16-224': (
'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json'
),
# See all DeiT models at https://huggingface.co/models?filter=deit
}
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : Optional[int] ='''deit'''
def __init__( self: Optional[int] , __a: Optional[int]=768 , __a: int=12 , __a: List[Any]=12 , __a: List[Any]=3_072 , __a: Any="gelu" , __a: Optional[Any]=0.0 , __a: Dict=0.0 , __a: Dict=0.02 , __a: int=1e-1_2 , __a: int=224 , __a: Tuple=16 , __a: List[Any]=3 , __a: Union[str, Any]=True , __a: Union[str, Any]=16 , **__a: int , )-> Union[str, Any]:
super().__init__(**__a )
lowerCamelCase : List[str] = hidden_size
lowerCamelCase : Optional[int] = num_hidden_layers
lowerCamelCase : Dict = num_attention_heads
lowerCamelCase : List[str] = intermediate_size
lowerCamelCase : Optional[Any] = hidden_act
lowerCamelCase : int = hidden_dropout_prob
lowerCamelCase : Tuple = attention_probs_dropout_prob
lowerCamelCase : List[str] = initializer_range
lowerCamelCase : str = layer_norm_eps
lowerCamelCase : List[str] = image_size
lowerCamelCase : int = patch_size
lowerCamelCase : Dict = num_channels
lowerCamelCase : Tuple = qkv_bias
lowerCamelCase : Tuple = encoder_stride
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : str =version.parse('''1.11''')
@property
def a__ ( self: Optional[int] )-> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
] )
@property
def a__ ( self: Union[str, Any] )-> float:
return 1e-4
| 222 | 1 |
import unittest
import numpy as np
import torch
from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class __a ( unittest.TestCase ):
@property
def SCREAMING_SNAKE_CASE__ ( self ) -> str:
'''simple docstring'''
torch.manual_seed(0 )
lowercase__: Dict = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , )
return model
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
lowercase__: List[Any] = self.dummy_uncond_unet
lowercase__: int = KarrasVeScheduler()
lowercase__: Dict = KarrasVePipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ )
pipe.to(lowerCAmelCase__ )
pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowercase__: Dict = torch.manual_seed(0 )
lowercase__: List[str] = pipe(num_inference_steps=2 , generator=lowerCAmelCase__ , output_type='numpy' ).images
lowercase__: List[str] = torch.manual_seed(0 )
lowercase__: str = pipe(num_inference_steps=2 , generator=lowerCAmelCase__ , output_type='numpy' , return_dict=lowerCAmelCase__ )[0]
lowercase__: Union[str, Any] = image[0, -3:, -3:, -1]
lowercase__: str = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
lowercase__: Union[str, Any] = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
@slow
@require_torch
class __a ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE__ ( self ) -> str:
'''simple docstring'''
lowercase__: List[str] = 'google/ncsnpp-celebahq-256'
lowercase__: Optional[int] = UNetaDModel.from_pretrained(lowerCAmelCase__ )
lowercase__: Dict = KarrasVeScheduler()
lowercase__: str = KarrasVePipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ )
pipe.to(lowerCAmelCase__ )
pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowercase__: Optional[int] = torch.manual_seed(0 )
lowercase__: str = pipe(num_inference_steps=20 , generator=lowerCAmelCase__ , output_type='numpy' ).images
lowercase__: List[str] = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
lowercase__: List[str] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 719 |
import unittest
from transformers import PegasusTokenizer, PegasusTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__lowerCAmelCase = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''')
@require_sentencepiece
@require_tokenizers
class __a ( __UpperCamelCase , unittest.TestCase ):
__lowercase : int = PegasusTokenizer
__lowercase : int = PegasusTokenizerFast
__lowercase : Dict = True
__lowercase : Union[str, Any] = True
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowercase__: Dict = PegasusTokenizer(lowerCAmelCase__ )
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]:
'''simple docstring'''
return PegasusTokenizer.from_pretrained('google/pegasus-large' )
def SCREAMING_SNAKE_CASE__ ( self , **lowerCAmelCase__ ) -> PegasusTokenizer:
'''simple docstring'''
return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Union[str, Any]:
'''simple docstring'''
return ("This is a test", "This is a test")
def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]:
'''simple docstring'''
lowercase__: Tuple = '</s>'
lowercase__: Tuple = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) , lowerCAmelCase__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) , lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ) -> Any:
'''simple docstring'''
lowercase__: Optional[int] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '<pad>' )
self.assertEqual(vocab_keys[1] , '</s>' )
self.assertEqual(vocab_keys[-1] , 'v' )
self.assertEqual(len(lowerCAmelCase__ ) , 1_103 )
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 1_103 )
def SCREAMING_SNAKE_CASE__ ( self ) -> Dict:
'''simple docstring'''
lowercase__: Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname )
lowercase__: List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname )
lowercase__: Any = (
'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important'
' </s> <pad> <pad> <pad>'
)
lowercase__: Any = rust_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0]
lowercase__: str = py_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0]
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ) -> int:
'''simple docstring'''
lowercase__: Optional[int] = self._large_tokenizer
# <mask_1> masks whole sentence while <mask_2> masks single word
lowercase__: Optional[int] = '<mask_1> To ensure a <mask_2> flow of bank resolutions.'
lowercase__: Any = [2, 413, 615, 114, 3, 1_971, 113, 1_679, 10_710, 107, 1]
lowercase__: int = tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ ).input_ids[0]
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ) -> int:
'''simple docstring'''
lowercase__: Union[str, Any] = self._large_tokenizer
# The tracebacks for the following asserts are **better** without messages or self.assertEqual
assert tokenizer.vocab_size == 96_103
assert tokenizer.pad_token_id == 0
assert tokenizer.eos_token_id == 1
assert tokenizer.offset == 103
assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105
assert tokenizer.unk_token == "<unk>"
assert tokenizer.model_max_length == 1_024
lowercase__: Tuple = 'To ensure a smooth flow of bank resolutions.'
lowercase__: Tuple = [413, 615, 114, 2_291, 1_971, 113, 1_679, 10_710, 107, 1]
lowercase__: Tuple = tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ ).input_ids[0]
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"]
@require_torch
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
lowercase__: Optional[Any] = ['This is going to be way too long.' * 150, 'short example']
lowercase__: Optional[int] = ['not super long but more than 5 tokens', 'tiny']
lowercase__: str = self._large_tokenizer(lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' )
lowercase__: Tuple = self._large_tokenizer(
text_target=lowerCAmelCase__ , max_length=5 , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' )
assert batch.input_ids.shape == (2, 1_024)
assert batch.attention_mask.shape == (2, 1_024)
assert targets["input_ids"].shape == (2, 5)
assert len(lowerCAmelCase__ ) == 2 # input_ids, attention_mask.
@slow
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
# fmt: off
lowercase__: Union[str, Any] = {'input_ids': [[38_979, 143, 18_485, 606, 130, 26_669, 87_686, 121, 54_189, 1_129, 111, 26_669, 87_686, 121, 9_114, 14_787, 121, 13_249, 158, 592, 956, 121, 14_621, 31_576, 143, 62_613, 108, 9_688, 930, 43_430, 11_562, 62_613, 304, 108, 11_443, 897, 108, 9_314, 17_415, 63_399, 108, 11_443, 7_614, 18_316, 118, 4_284, 7_148, 12_430, 143, 1_400, 25_703, 158, 111, 4_284, 7_148, 11_772, 143, 21_297, 1_064, 158, 122, 204, 3_506, 1_754, 1_133, 14_787, 1_581, 115, 33_224, 4_482, 111, 1_355, 110, 29_173, 317, 50_833, 108, 20_147, 94_665, 111, 77_198, 107, 1], [110, 62_613, 117, 638, 112, 1_133, 121, 20_098, 1_355, 79_050, 13_872, 135, 1_596, 53_541, 1_352, 141, 13_039, 5_542, 124, 302, 518, 111, 268, 2_956, 115, 149, 4_427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1_235, 2_799, 18_289, 17_780, 204, 109, 9_474, 1_296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowerCAmelCase__ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , )
@require_sentencepiece
@require_tokenizers
class __a ( __UpperCamelCase , unittest.TestCase ):
__lowercase : Union[str, Any] = PegasusTokenizer
__lowercase : Union[str, Any] = PegasusTokenizerFast
__lowercase : int = True
__lowercase : Union[str, Any] = True
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowercase__: Optional[Any] = PegasusTokenizer(lowerCAmelCase__ , offset=0 , mask_token_sent=lowerCAmelCase__ , mask_token='[MASK]' )
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple:
'''simple docstring'''
return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' )
def SCREAMING_SNAKE_CASE__ ( self , **lowerCAmelCase__ ) -> PegasusTokenizer:
'''simple docstring'''
return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ )
def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Optional[Any]:
'''simple docstring'''
return ("This is a test", "This is a test")
def SCREAMING_SNAKE_CASE__ ( self ) -> Dict:
'''simple docstring'''
lowercase__: int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname )
lowercase__: List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname )
lowercase__: List[Any] = (
'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>'
' <pad> <pad> <pad>'
)
lowercase__: Tuple = rust_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0]
lowercase__: str = py_tokenizer([raw_input_str] , return_tensors=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ).input_ids[0]
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
@require_torch
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
'''simple docstring'''
lowercase__: Optional[Any] = ['This is going to be way too long.' * 1_000, 'short example']
lowercase__: Optional[Any] = ['not super long but more than 5 tokens', 'tiny']
lowercase__: Optional[int] = self._large_tokenizer(lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' )
lowercase__: Tuple = self._large_tokenizer(
text_target=lowerCAmelCase__ , max_length=5 , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors='pt' )
assert batch.input_ids.shape == (2, 4_096)
assert batch.attention_mask.shape == (2, 4_096)
assert targets["input_ids"].shape == (2, 5)
assert len(lowerCAmelCase__ ) == 2 # input_ids, attention_mask.
def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]:
'''simple docstring'''
lowercase__: Union[str, Any] = (
'This is an example string that is used to test the original TF implementation against the HF'
' implementation'
)
lowercase__: int = self._large_tokenizer(lowerCAmelCase__ ).input_ids
self.assertListEqual(
lowerCAmelCase__ , [182, 117, 142, 587, 4_211, 120, 117, 263, 112, 804, 109, 856, 25_016, 3_137, 464, 109, 26_955, 3_137, 1] , )
| 335 | 0 |
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
if openai_config_file == "":
SCREAMING_SNAKE_CASE_ = OpenAIGPTConfig()
else:
SCREAMING_SNAKE_CASE_ = OpenAIGPTConfig.from_json_file(lowercase_ )
SCREAMING_SNAKE_CASE_ = OpenAIGPTModel(lowercase_ )
# Load weights from numpy
load_tf_weights_in_openai_gpt(lowercase_ , lowercase_ , lowercase_ )
# Save pytorch-model
SCREAMING_SNAKE_CASE_ = pytorch_dump_folder_path + "/" + WEIGHTS_NAME
SCREAMING_SNAKE_CASE_ = pytorch_dump_folder_path + "/" + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(lowercase_ , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
A : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--openai_checkpoint_folder_path",
default=None,
type=str,
required=True,
help="Path to the TensorFlow checkpoint path.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument(
"--openai_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained OpenAI model. \n"
"This specifies the model architecture."
),
)
A : Optional[Any] = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 140 |
from math import sqrt
import numpy as np
from sympy import symbols
# Coefficient
# Speed of light (m/s)
_lowerCamelCase : str = 299792458
# Symbols
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : int = symbols("""ct x y z""")
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> float:
"""simple docstring"""
if velocity > c:
raise ValueError('''Speed must not exceed light speed 299,792,458 [m/s]!''' )
elif velocity < 1:
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError('''Speed must be greater than or equal to 1!''' )
return velocity / c
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> float:
"""simple docstring"""
return 1 / sqrt(1 - beta(lowercase_ ) ** 2 )
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> np.ndarray:
"""simple docstring"""
return np.array(
[
[gamma(lowercase_ ), -gamma(lowercase_ ) * beta(lowercase_ ), 0, 0],
[-gamma(lowercase_ ) * beta(lowercase_ ), gamma(lowercase_ ), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
] )
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = None ) -> np.ndarray:
"""simple docstring"""
if event is None:
A__ = np.array([ct, x, y, z] ) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)
return transformation_matrix(lowercase_ ) @ event
if __name__ == "__main__":
import doctest
doctest.testmod()
# Example of symbolic vector:
_lowerCamelCase : Tuple = transform(29979245)
print("""Example of four vector: """)
print(F'''ct\' = {four_vector[0]}''')
print(F'''x\' = {four_vector[1]}''')
print(F'''y\' = {four_vector[2]}''')
print(F'''z\' = {four_vector[3]}''')
# Substitute symbols with numerical values
_lowerCamelCase : int = {ct: c, x: 1, y: 1, z: 1}
_lowerCamelCase : Any = [four_vector[i].subs(sub_dict) for i in range(4)]
print(F'''\n{numerical_vector}''')
| 87 | 0 |
"""simple docstring"""
# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
# ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
# --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
# --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
# 1. --tf32 0 --fp16 0
# 2. --tf32 0 --fp16 1
# 3. --tf32 0 --bf16 1
# 4. --tf32 1 --fp16 0
# 5. --tf32 1 --fp16 1
# 6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
# --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
# --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
# 1. --tf32 0
# 2. --tf32 0 --fp16
# 3. --tf32 0 --bf16
# 4. --tf32 1
# 5. --tf32 1 --fp16
# 6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
# `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation | Train | Diff | Train |
# | | samples | % | loss |
# | | per | | |
# | | second | | |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0 | 285.11 | 0 | 2.51 |
# | --tf32 1 | 342.09 | 20 | 2.51 |
# | --fp16 --tf32 0 | 423.49 | 49 | 2.51 |
# | --fp16 --tf32 1 | 423.13 | 48 | 2.51 |
# | --bf16 --tf32 0 | 416.80 | 46 | 2.52 |
# | --bf16 --tf32 1 | 415.87 | 46 | 2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
# --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#
import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean
import pandas as pd
import torch
from tqdm import tqdm
import transformers
__magic_name__ = float("""nan""")
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Any , SCREAMING_SNAKE_CASE_ : Any ):
lowerCamelCase__ = sys.stdout
lowerCamelCase__ = open(_A , """a""" )
def __getattr__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict ):
return getattr(self.stdout , _A )
def __UpperCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ):
self.stdout.write(_A )
# strip tqdm codes
self.file.write(re.sub(r"""^.*\r""" , """""" , _A , 0 , re.M ) )
def _A ( __lowercase=80 , __lowercase=False ):
"""simple docstring"""
lowerCamelCase__ = []
# deal with critical env vars
lowerCamelCase__ = ["""CUDA_VISIBLE_DEVICES"""]
for key in env_keys:
lowerCamelCase__ = os.environ.get(UpperCAmelCase__ , UpperCAmelCase__ )
if val is not None:
cmd.append(f"""{key}={val}""" )
# python executable (not always needed if the script is executable)
lowerCamelCase__ = sys.executable if full_python_path else sys.executable.split("""/""" )[-1]
cmd.append(UpperCAmelCase__ )
# now the normal args
cmd += list(map(shlex.quote , sys.argv ) )
# split up into up to MAX_WIDTH lines with shell multi-line escapes
lowerCamelCase__ = []
lowerCamelCase__ = """"""
while len(UpperCAmelCase__ ) > 0:
current_line += f"""{cmd.pop(0 )} """
if len(UpperCAmelCase__ ) == 0 or len(UpperCAmelCase__ ) + len(cmd[0] ) + 1 > max_width - 1:
lines.append(UpperCAmelCase__ )
lowerCamelCase__ = """"""
return "\\\n".join(UpperCAmelCase__ )
def _A ( __lowercase , __lowercase ):
"""simple docstring"""
lowerCamelCase__ = re.sub(r"""[\\\n]+""" , """ """ , args.base_cmd )
# remove --output_dir if any and set our own
lowerCamelCase__ = re.sub("""--output_dir\s+[^\s]+""" , """""" , args.base_cmd )
args.base_cmd += f""" --output_dir {output_dir}"""
# ensure we have --overwrite_output_dir
lowerCamelCase__ = re.sub("""--overwrite_output_dir\s+""" , """""" , args.base_cmd )
args.base_cmd += " --overwrite_output_dir"
return [sys.executable] + shlex.split(args.base_cmd )
def _A ( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ):
"""simple docstring"""
if 0:
import random
from time import sleep
sleep(0 )
return dict(
{k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22] )} , )
lowerCamelCase__ = subprocess.run(UpperCAmelCase__ , capture_output=UpperCAmelCase__ , text=UpperCAmelCase__ )
if verbose:
print("""STDOUT""" , result.stdout )
print("""STDERR""" , result.stderr )
# save the streams
lowerCamelCase__ = variation.replace(""" """ , """-""" )
with open(Path(UpperCAmelCase__ ) / f"""log.{prefix}.stdout.txt""" , """w""" ) as f:
f.write(result.stdout )
with open(Path(UpperCAmelCase__ ) / f"""log.{prefix}.stderr.txt""" , """w""" ) as f:
f.write(result.stderr )
if result.returncode != 0:
if verbose:
print("""failed""" )
return {target_metric_key: nan}
with io.open(f"""{output_dir}/all_results.json""" , """r""" , encoding="""utf-8""" ) as f:
lowerCamelCase__ = json.load(UpperCAmelCase__ )
# filter out just the keys we want
return {k: v for k, v in metrics.items() if k in metric_keys}
def _A ( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , ):
"""simple docstring"""
lowerCamelCase__ = []
lowerCamelCase__ = []
lowerCamelCase__ = f"""{id}: {variation:<{longest_variation_len}}"""
lowerCamelCase__ = f"""{preamble}: """
lowerCamelCase__ = set(report_metric_keys + [target_metric_key] )
for i in tqdm(range(UpperCAmelCase__ ) , desc=UpperCAmelCase__ , leave=UpperCAmelCase__ ):
lowerCamelCase__ = process_run_single(
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
lowerCamelCase__ = single_run_metrics[target_metric_key]
if not math.isnan(UpperCAmelCase__ ):
metrics.append(UpperCAmelCase__ )
results.append(UpperCAmelCase__ )
outcome += "✓"
else:
outcome += "✘"
lowerCamelCase__ = f"""\33[2K\r{outcome}"""
if len(UpperCAmelCase__ ) > 0:
lowerCamelCase__ = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()}
lowerCamelCase__ = round(mean_metrics[target_metric_key] , 2 )
lowerCamelCase__ = f"""{outcome} {mean_target}"""
if len(UpperCAmelCase__ ) > 1:
results_str += f""" {tuple(round(UpperCAmelCase__ , 2 ) for x in results )}"""
print(UpperCAmelCase__ )
lowerCamelCase__ = variation
return mean_metrics
else:
print(UpperCAmelCase__ )
return {variation_key: variation, target_metric_key: nan}
def _A ( ):
"""simple docstring"""
lowerCamelCase__ = torch.cuda.get_device_properties(torch.device("""cuda""" ) )
return f"""
Datetime : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' )}
Software:
transformers: {transformers.__version__}
torch : {torch.__version__}
cuda : {torch.version.cuda}
python : {platform.python_version()}
Hardware:
{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB
"""
def _A ( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ):
"""simple docstring"""
lowerCamelCase__ = pd.DataFrame(UpperCAmelCase__ )
lowerCamelCase__ = """variation"""
lowerCamelCase__ = """diff_%"""
lowerCamelCase__ = nan
if base_variation is not None and len(df[df[variation_key] == base_variation] ):
# this may still return nan
lowerCamelCase__ = df.loc[df[variation_key] == base_variation][target_metric_key].item()
if math.isnan(UpperCAmelCase__ ):
# as a fallback, use the minimal value as the sentinel
lowerCamelCase__ = df.loc[df[target_metric_key] != nan][target_metric_key].min()
# create diff column if possible
if not math.isnan(UpperCAmelCase__ ):
lowerCamelCase__ = df.apply(
lambda __lowercase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value )
if not math.isnan(r[target_metric_key] )
else 0 , axis="""columns""" , )
# re-order columns
lowerCamelCase__ = [variation_key, target_metric_key, diff_key, *report_metric_keys]
lowerCamelCase__ = df.reindex(UpperCAmelCase__ , axis="""columns""" ) # reorder cols
# capitalize
lowerCamelCase__ = df.rename(str.capitalize , axis="""columns""" )
# make the cols as narrow as possible
lowerCamelCase__ = df.rename(lambda __lowercase : c.replace("""_""" , """<br>""" ) , axis="""columns""" )
lowerCamelCase__ = df.rename(lambda __lowercase : c.replace("""_""" , """\n""" ) , axis="""columns""" )
lowerCamelCase__ = ["""""", """Copy between the cut-here-lines and paste as is to github or a forum"""]
report += ["----------8<-----------------8<--------"]
report += ["*** Results:", df_github.to_markdown(index=UpperCAmelCase__ , floatfmt=""".2f""" )]
report += ["```"]
report += ["*** Setup:", get_versions()]
report += ["*** The benchmark command line was:", get_original_command()]
report += ["```"]
report += ["----------8<-----------------8<--------"]
report += ["*** Results (console):", df_console.to_markdown(index=UpperCAmelCase__ , floatfmt=""".2f""" )]
print("""\n\n""".join(UpperCAmelCase__ ) )
def _A ( ):
"""simple docstring"""
lowerCamelCase__ = argparse.ArgumentParser()
parser.add_argument(
"""--base-cmd""" , default=UpperCAmelCase__ , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help="""Base cmd""" , )
parser.add_argument(
"""--variations""" , default=UpperCAmelCase__ , type=UpperCAmelCase__ , nargs="""+""" , required=UpperCAmelCase__ , help="""Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'""" , )
parser.add_argument(
"""--base-variation""" , default=UpperCAmelCase__ , type=UpperCAmelCase__ , help="""Baseline variation to compare to. if None the minimal target value will be used to compare against""" , )
parser.add_argument(
"""--target-metric-key""" , default=UpperCAmelCase__ , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second""" , )
parser.add_argument(
"""--report-metric-keys""" , default="""""" , type=UpperCAmelCase__ , help="""Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples""" , )
parser.add_argument(
"""--repeat-times""" , default=1 , type=UpperCAmelCase__ , help="""How many times to re-run each variation - an average will be reported""" , )
parser.add_argument(
"""--output_dir""" , default="""output_benchmark""" , type=UpperCAmelCase__ , help="""The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked""" , )
parser.add_argument(
"""--verbose""" , default=UpperCAmelCase__ , action="""store_true""" , help="""Whether to show the outputs of each run or just the benchmark progress""" , )
lowerCamelCase__ = parser.parse_args()
lowerCamelCase__ = args.output_dir
Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ )
lowerCamelCase__ = get_base_command(UpperCAmelCase__ , UpperCAmelCase__ )
# split each dimension into its --foo variations
lowerCamelCase__ = [list(map(str.strip , re.split(r"""\|""" , UpperCAmelCase__ ) ) ) for x in args.variations]
# build a cartesian product of dimensions and convert those back into cmd-line arg strings,
# while stripping white space for inputs that were empty
lowerCamelCase__ = list(map(str.strip , map(""" """.join , itertools.product(*UpperCAmelCase__ ) ) ) )
lowerCamelCase__ = max(len(UpperCAmelCase__ ) for x in variations )
# split wanted keys
lowerCamelCase__ = args.report_metric_keys.split()
# capture prints into a log file for convenience
lowerCamelCase__ = f"""benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S' )}.txt"""
print(f"""\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt""" )
print(f"""and this script's output is also piped into {report_fn}""" )
lowerCamelCase__ = Tee(UpperCAmelCase__ )
print(f"""\n*** Running {len(UpperCAmelCase__ )} benchmarks:""" )
print(f"""Base command: {' '.join(UpperCAmelCase__ )}""" )
lowerCamelCase__ = """variation"""
lowerCamelCase__ = []
for id, variation in enumerate(tqdm(UpperCAmelCase__ , desc="""Total completion: """ , leave=UpperCAmelCase__ ) ):
lowerCamelCase__ = base_cmd + variation.split()
results.append(
process_run(
id + 1 , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , args.target_metric_key , UpperCAmelCase__ , args.repeat_times , UpperCAmelCase__ , args.verbose , ) )
process_results(UpperCAmelCase__ , args.target_metric_key , UpperCAmelCase__ , args.base_variation , UpperCAmelCase__ )
if __name__ == "__main__":
main()
| 714 |
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ : # Public class to implement a graph
def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[list[bool]] ):
lowerCamelCase__ = row
lowerCamelCase__ = col
lowerCamelCase__ = graph
def __UpperCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[list[bool]] ):
return (
0 <= i < self.ROW
and 0 <= j < self.COL
and not visited[i][j]
and self.graph[i][j]
)
def __UpperCAmelCase ( self : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[list[bool]] ):
# Checking all 8 elements surrounding nth element
lowerCamelCase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order
lowerCamelCase__ = [-1, 0, 1, -1, 1, -1, 0, 1]
lowerCamelCase__ = True # Make those cells visited
for k in range(8 ):
if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE_ ):
self.diffs(i + row_nbr[k] , j + col_nbr[k] , SCREAMING_SNAKE_CASE_ )
def __UpperCAmelCase ( self : int ): # And finally, count all islands.
lowerCamelCase__ = [[False for j in range(self.COL )] for i in range(self.ROW )]
lowerCamelCase__ = 0
for i in range(self.ROW ):
for j in range(self.COL ):
if visited[i][j] is False and self.graph[i][j] == 1:
self.diffs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
count += 1
return count
| 258 | 0 |
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def _a ( a :int ) -> bool:
a = int(number**0.5 )
return number == sq * sq
def _a ( a :int , a :int , a :int , a :int , a :int , a :int ) -> tuple[int, int]:
a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
a = x_den * y_den * z_den
a = gcd(a , a )
top //= hcf
bottom //= hcf
return top, bottom
def _a ( a :int = 35 ) -> int:
a = set()
a = 42
a = Fraction(0 )
a = 42
for x_num in range(1 , order + 1 ):
for x_den in range(x_num + 1 , order + 1 ):
for y_num in range(1 , order + 1 ):
for y_den in range(y_num + 1 , order + 1 ):
# n=1
a = x_num * y_den + x_den * y_num
a = x_den * y_den
a = gcd(a , a )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
a , a , a , a , a , a )
unique_s.add(a )
# n=2
a = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
a = x_den * x_den * y_den * y_den
if is_sq(a ) and is_sq(a ):
a = int(sqrt(a ) )
a = int(sqrt(a ) )
a = gcd(a , a )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
a , a , a , a , a , a )
unique_s.add(a )
# n=-1
a = x_num * y_num
a = x_den * y_num + x_num * y_den
a = gcd(a , a )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
a , a , a , a , a , a )
unique_s.add(a )
# n=2
a = x_num * x_num * y_num * y_num
a = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(a ) and is_sq(a ):
a = int(sqrt(a ) )
a = int(sqrt(a ) )
a = gcd(a , a )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
a , a , a , a , a , a )
unique_s.add(a )
for num, den in unique_s:
total += Fraction(a , a )
return total.denominator + total.numerator
if __name__ == "__main__":
print(f"""{solution() = }""")
| 117 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaInpaintPipeline,
KandinskyVaaPriorPipeline,
UNetaDConditionModel,
VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class lowercase_ ( lowercase , unittest.TestCase ):
'''simple docstring'''
__snake_case = KandinskyVaaInpaintPipeline
__snake_case = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
__snake_case = [
'''image_embeds''',
'''negative_image_embeds''',
'''image''',
'''mask_image''',
]
__snake_case = [
'''generator''',
'''height''',
'''width''',
'''latents''',
'''guidance_scale''',
'''num_inference_steps''',
'''return_dict''',
'''guidance_scale''',
'''num_images_per_prompt''',
'''output_type''',
'''return_dict''',
]
__snake_case = False
@property
def __lowerCAmelCase ( self : Optional[int] ) ->Tuple:
"""simple docstring"""
return 32
@property
def __lowerCAmelCase ( self : Optional[Any] ) ->Dict:
"""simple docstring"""
return 32
@property
def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]:
"""simple docstring"""
return self.time_input_dim
@property
def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]:
"""simple docstring"""
return self.time_input_dim * 4
@property
def __lowerCAmelCase ( self : Any ) ->Optional[int]:
"""simple docstring"""
return 100
@property
def __lowerCAmelCase ( self : Tuple ) ->Optional[int]:
"""simple docstring"""
torch.manual_seed(0 )
a = {
'''in_channels''': 9,
# Out channels is double in channels because predicts mean and variance
'''out_channels''': 8,
'''addition_embed_type''': '''image''',
'''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
'''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
'''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
'''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
'''layers_per_block''': 1,
'''encoder_hid_dim''': self.text_embedder_hidden_size,
'''encoder_hid_dim_type''': '''image_proj''',
'''cross_attention_dim''': self.cross_attention_dim,
'''attention_head_dim''': 4,
'''resnet_time_scale_shift''': '''scale_shift''',
'''class_embed_type''': None,
}
a = UNetaDConditionModel(**__UpperCAmelCase )
return model
@property
def __lowerCAmelCase ( self : List[Any] ) ->List[Any]:
"""simple docstring"""
return {
"block_out_channels": [32, 64],
"down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": [
"AttnUpDecoderBlock2D",
"UpDecoderBlock2D",
],
"vq_embed_dim": 4,
}
@property
def __lowerCAmelCase ( self : str ) ->List[Any]:
"""simple docstring"""
torch.manual_seed(0 )
a = VQModel(**self.dummy_movq_kwargs )
return model
def __lowerCAmelCase ( self : Optional[Any] ) ->Any:
"""simple docstring"""
a = self.dummy_unet
a = self.dummy_movq
a = DDIMScheduler(
num_train_timesteps=1_000 , beta_schedule='''linear''' , beta_start=0.00085 , beta_end=0.012 , clip_sample=__UpperCAmelCase , set_alpha_to_one=__UpperCAmelCase , steps_offset=1 , prediction_type='''epsilon''' , thresholding=__UpperCAmelCase , )
a = {
'''unet''': unet,
'''scheduler''': scheduler,
'''movq''': movq,
}
return components
def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[str] , __UpperCAmelCase : int=0 ) ->Optional[int]:
"""simple docstring"""
a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase )
a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
__UpperCAmelCase )
# create init_image
a = floats_tensor((1, 3, 64, 64) , rng=random.Random(__UpperCAmelCase ) ).to(__UpperCAmelCase )
a = image.cpu().permute(0 , 2 , 3 , 1 )[0]
a = Image.fromarray(np.uinta(__UpperCAmelCase ) ).convert('''RGB''' ).resize((256, 256) )
# create mask
a = np.ones((64, 64) , dtype=np.floataa )
a = 0
if str(__UpperCAmelCase ).startswith('''mps''' ):
a = torch.manual_seed(__UpperCAmelCase )
else:
a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase )
a = {
'''image''': init_image,
'''mask_image''': mask,
'''image_embeds''': image_embeds,
'''negative_image_embeds''': negative_image_embeds,
'''generator''': generator,
'''height''': 64,
'''width''': 64,
'''num_inference_steps''': 2,
'''guidance_scale''': 4.0,
'''output_type''': '''np''',
}
return inputs
def __lowerCAmelCase ( self : Dict ) ->int:
"""simple docstring"""
a = '''cpu'''
a = self.get_dummy_components()
a = self.pipeline_class(**__UpperCAmelCase )
a = pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) )
a = output.images
a = pipe(
**self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0]
a = image[0, -3:, -3:, -1]
a = image_from_tuple[0, -3:, -3:, -1]
print(F"""image.shape {image.shape}""" )
assert image.shape == (1, 64, 64, 3)
a = np.array(
[0.50775903, 0.49527195, 0.48824543, 0.50192237, 0.48644906, 0.49373814, 0.4780598, 0.47234827, 0.48327848] )
assert (
np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""
def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]:
"""simple docstring"""
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
@slow
@require_torch_gpu
class lowercase_ ( unittest.TestCase ):
'''simple docstring'''
def __lowerCAmelCase ( self : Any ) ->List[Any]:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __lowerCAmelCase ( self : List[str] ) ->str:
"""simple docstring"""
a = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy''' )
a = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' )
a = np.ones((768, 768) , dtype=np.floataa )
a = 0
a = '''a hat'''
a = KandinskyVaaPriorPipeline.from_pretrained(
'''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa )
pipe_prior.to(__UpperCAmelCase )
a = KandinskyVaaInpaintPipeline.from_pretrained(
'''kandinsky-community/kandinsky-2-2-decoder-inpaint''' , torch_dtype=torch.floataa )
a = pipeline.to(__UpperCAmelCase )
pipeline.set_progress_bar_config(disable=__UpperCAmelCase )
a = torch.Generator(device='''cpu''' ).manual_seed(0 )
a , a = pipe_prior(
__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple()
a = pipeline(
image=__UpperCAmelCase , mask_image=__UpperCAmelCase , image_embeds=__UpperCAmelCase , negative_image_embeds=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=100 , height=768 , width=768 , output_type='''np''' , )
a = output.images[0]
assert image.shape == (768, 768, 3)
assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
| 117 | 1 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import CLIPImageProcessor, CLIPProcessor
@require_vision
class lowercase ( unittest.TestCase ):
"""simple docstring"""
def __UpperCAmelCase ( self : Union[str, Any] ):
'''simple docstring'''
_snake_case : Optional[Any] = tempfile.mkdtemp()
# fmt: off
_snake_case : Optional[Any] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
# fmt: on
_snake_case : str = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) )
_snake_case : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
_snake_case : Optional[Any] = {'unk_token': '<unk>'}
_snake_case : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
_snake_case : Union[str, Any] = 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(lowerCamelCase_ ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(lowerCamelCase_ ) )
_snake_case : Dict = {
'do_resize': True,
'size': 20,
'do_center_crop': True,
'crop_size': 18,
'do_normalize': True,
'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073],
'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711],
}
_snake_case : str = os.path.join(self.tmpdirname , lowerCamelCase_ )
with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp:
json.dump(lowerCamelCase_ , lowerCamelCase_ )
def __UpperCAmelCase ( self : Dict , **lowerCamelCase_ : Optional[Any] ):
'''simple docstring'''
return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase_ )
def __UpperCAmelCase ( self : List[Any] , **lowerCamelCase_ : int ):
'''simple docstring'''
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCamelCase_ )
def __UpperCAmelCase ( self : Optional[Any] , **lowerCamelCase_ : Tuple ):
'''simple docstring'''
return CLIPImageProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase_ )
def __UpperCAmelCase ( self : List[str] ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def __UpperCAmelCase ( self : Dict ):
'''simple docstring'''
_snake_case : List[Any] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
_snake_case : int = [Image.fromarray(np.moveaxis(lowerCamelCase_ , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def __UpperCAmelCase ( self : Any ):
'''simple docstring'''
_snake_case : List[Any] = self.get_tokenizer()
_snake_case : Dict = self.get_rust_tokenizer()
_snake_case : List[Any] = self.get_image_processor()
_snake_case : Dict = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
processor_slow.save_pretrained(self.tmpdirname )
_snake_case : str = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCamelCase_ )
_snake_case : Tuple = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
processor_fast.save_pretrained(self.tmpdirname )
_snake_case : Tuple = CLIPProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() )
self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() )
self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() )
self.assertIsInstance(processor_slow.tokenizer , lowerCamelCase_ )
self.assertIsInstance(processor_fast.tokenizer , lowerCamelCase_ )
self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor_slow.image_processor , lowerCamelCase_ )
self.assertIsInstance(processor_fast.image_processor , lowerCamelCase_ )
def __UpperCAmelCase ( self : int ):
'''simple docstring'''
_snake_case : Dict = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
_snake_case : Any = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
_snake_case : Any = self.get_image_processor(do_normalize=lowerCamelCase_ , padding_value=1.0 )
_snake_case : str = CLIPProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=lowerCamelCase_ , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , lowerCamelCase_ )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , lowerCamelCase_ )
def __UpperCAmelCase ( self : List[str] ):
'''simple docstring'''
_snake_case : List[Any] = self.get_image_processor()
_snake_case : Optional[Any] = self.get_tokenizer()
_snake_case : int = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
_snake_case : Optional[int] = self.prepare_image_inputs()
_snake_case : Tuple = image_processor(lowerCamelCase_ , return_tensors='np' )
_snake_case : List[str] = processor(images=lowerCamelCase_ , return_tensors='np' )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 )
def __UpperCAmelCase ( self : List[Any] ):
'''simple docstring'''
_snake_case : Optional[Any] = self.get_image_processor()
_snake_case : List[Any] = self.get_tokenizer()
_snake_case : str = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
_snake_case : Optional[Any] = 'lower newer'
_snake_case : List[str] = processor(text=lowerCamelCase_ )
_snake_case : str = tokenizer(lowerCamelCase_ )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def __UpperCAmelCase ( self : List[str] ):
'''simple docstring'''
_snake_case : Optional[Any] = self.get_image_processor()
_snake_case : Optional[Any] = self.get_tokenizer()
_snake_case : Any = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
_snake_case : Dict = 'lower newer'
_snake_case : Optional[Any] = self.prepare_image_inputs()
_snake_case : Dict = processor(text=lowerCamelCase_ , images=lowerCamelCase_ )
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] )
# test if it raises when no input is passed
with pytest.raises(lowerCamelCase_ ):
processor()
def __UpperCAmelCase ( self : Optional[int] ):
'''simple docstring'''
_snake_case : Union[str, Any] = self.get_image_processor()
_snake_case : int = self.get_tokenizer()
_snake_case : List[Any] = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
_snake_case : Dict = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
_snake_case : Optional[Any] = processor.batch_decode(lowerCamelCase_ )
_snake_case : Optional[Any] = tokenizer.batch_decode(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
def __UpperCAmelCase ( self : Any ):
'''simple docstring'''
_snake_case : Tuple = self.get_image_processor()
_snake_case : List[str] = self.get_tokenizer()
_snake_case : Dict = CLIPProcessor(tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ )
_snake_case : List[Any] = 'lower newer'
_snake_case : Optional[int] = self.prepare_image_inputs()
_snake_case : List[str] = processor(text=lowerCamelCase_ , images=lowerCamelCase_ )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 652 |
from __future__ import annotations
def A__( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
_snake_case : Dict = list(range(len(__lowerCAmelCase ) ) )
_snake_case : Optional[int] = [v / w for v, w in zip(__lowerCAmelCase , __lowerCAmelCase )]
index.sort(key=lambda __lowerCAmelCase : ratio[i] , reverse=__lowerCAmelCase )
_snake_case : float = 0
_snake_case : list[float] = [0] * len(__lowerCAmelCase )
for i in index:
if weight[i] <= capacity:
_snake_case : List[Any] = 1
max_value += value[i]
capacity -= weight[i]
else:
_snake_case : Any = capacity / weight[i]
max_value += value[i] * capacity / weight[i]
break
return max_value, fractions
if __name__ == "__main__":
import doctest
doctest.testmod()
| 652 | 1 |
"""simple docstring"""
from random import randint
from tempfile import TemporaryFile
import numpy as np
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ : Optional[int] = 0
if start < end:
SCREAMING_SNAKE_CASE__ : Any = randint(__lowerCAmelCase , __lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Any = a[end]
SCREAMING_SNAKE_CASE__ : Union[str, Any] = a[pivot]
SCREAMING_SNAKE_CASE__ : Optional[int] = temp
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = _in_place_partition(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
count += _in_place_quick_sort(__lowerCAmelCase , __lowerCAmelCase , p - 1 )
count += _in_place_quick_sort(__lowerCAmelCase , p + 1 , __lowerCAmelCase )
return count
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int:
SCREAMING_SNAKE_CASE__ : str = 0
SCREAMING_SNAKE_CASE__ : Dict = randint(__lowerCAmelCase , __lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Optional[Any] = a[end]
SCREAMING_SNAKE_CASE__ : Dict = a[pivot]
SCREAMING_SNAKE_CASE__ : Tuple = temp
SCREAMING_SNAKE_CASE__ : int = start - 1
for index in range(__lowerCAmelCase , __lowerCAmelCase ):
count += 1
if a[index] < a[end]: # check if current val is less than pivot value
SCREAMING_SNAKE_CASE__ : List[str] = new_pivot_index + 1
SCREAMING_SNAKE_CASE__ : List[str] = a[new_pivot_index]
SCREAMING_SNAKE_CASE__ : Optional[int] = a[index]
SCREAMING_SNAKE_CASE__ : Any = temp
SCREAMING_SNAKE_CASE__ : Optional[Any] = a[new_pivot_index + 1]
SCREAMING_SNAKE_CASE__ : Optional[int] = a[end]
SCREAMING_SNAKE_CASE__ : Dict = temp
return new_pivot_index + 1, count
a :List[Any] = TemporaryFile()
a :Tuple = 100 # 1000 elements are to be sorted
a ,a :Tuple = 0, 1 # mean and standard deviation
a :Any = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print("The array is")
print(X)
outfile.seek(0) # using the same array
a :str = np.load(outfile)
a :Any = len(M) - 1
a :Tuple = _in_place_quick_sort(M, 0, r)
print(
"No of Comparisons for 100 elements selected from a standard normal distribution"
"is :"
)
print(z)
| 680 |
"""simple docstring"""
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from typing import List
from unittest.mock import Mock
import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset
from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType
class __a (UpperCamelCase_):
'''simple docstring'''
def __init__( self , _a ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = data
def __iter__( self ) -> Tuple:
"""simple docstring"""
for element in self.data:
yield element
def _lowercase ( __lowerCAmelCase=True ) -> str:
SCREAMING_SNAKE_CASE__ : str = Accelerator(even_batches=__lowerCAmelCase )
assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
return accelerator
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Optional[int]:
if iterable:
SCREAMING_SNAKE_CASE__ : int = DummyIterableDataset(torch.as_tensor(range(__lowerCAmelCase ) ) )
else:
SCREAMING_SNAKE_CASE__ : Optional[int] = TensorDataset(torch.as_tensor(range(__lowerCAmelCase ) ) )
SCREAMING_SNAKE_CASE__ : str = DataLoader(__lowerCAmelCase , batch_size=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : List[str] = accelerator.prepare(__lowerCAmelCase )
return dl
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) -> Tuple:
SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(accelerator=__lowerCAmelCase , dataset_size=__lowerCAmelCase , batch_size=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : List[str] = [len(batch[0] ) for batch in dl]
if accelerator.process_index == 0:
assert batch_sizes == process_0_expected_batch_sizes
elif accelerator.process_index == 1:
assert batch_sizes == process_1_expected_batch_sizes
def _lowercase ( ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ : Tuple = create_accelerator()
# without padding, we would expect a different number of batches
verify_dataloader_batch_sizes(
__lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , )
# without padding, we would expect the same number of batches, but different sizes
verify_dataloader_batch_sizes(
__lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , )
def _lowercase ( ) -> Dict:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator(even_batches=__lowerCAmelCase )
verify_dataloader_batch_sizes(
__lowerCAmelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , )
verify_dataloader_batch_sizes(
__lowerCAmelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , )
def _lowercase ( ) -> str:
SCREAMING_SNAKE_CASE__ : List[str] = create_accelerator(even_batches=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.Linear(1 , 1 )
SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Optional[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 )
SCREAMING_SNAKE_CASE__ : int = []
with accelerator.join_uneven_inputs([ddp_model] ):
for batch_idx, batch in enumerate(__lowerCAmelCase ):
SCREAMING_SNAKE_CASE__ : Optional[Any] = ddp_model(batch[0].float() )
SCREAMING_SNAKE_CASE__ : List[Any] = output.sum()
loss.backward()
batch_idxs.append(__lowerCAmelCase )
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
assert batch_idxs == [0, 1]
elif accelerator.process_index == 1:
assert batch_idxs == [0]
def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]:
with warnings.catch_warnings(record=__lowerCAmelCase ) as w:
with accelerator.join_uneven_inputs([Mock()] ):
pass
assert issubclass(w[-1].category , __lowerCAmelCase )
assert "only supported for multi-GPU" in str(w[-1].message )
def _lowercase ( ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ : Optional[Any] = True
SCREAMING_SNAKE_CASE__ : Optional[Any] = False
SCREAMING_SNAKE_CASE__ : Any = create_accelerator(even_batches=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Tuple = torch.nn.Linear(1 , 1 )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerator.prepare(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Tuple = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 )
SCREAMING_SNAKE_CASE__ : List[Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 )
with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ):
SCREAMING_SNAKE_CASE__ : List[Any] = train_dl.batch_sampler.even_batches
SCREAMING_SNAKE_CASE__ : str = valid_dl.batch_sampler.even_batches
assert train_dl_overridden_value == overridden_even_batches
assert valid_dl_overridden_value == overridden_even_batches
assert train_dl.batch_sampler.even_batches == default_even_batches
assert valid_dl.batch_sampler.even_batches == default_even_batches
def _lowercase ( ) -> Tuple:
SCREAMING_SNAKE_CASE__ : List[Any] = True
SCREAMING_SNAKE_CASE__ : List[Any] = False
SCREAMING_SNAKE_CASE__ : int = create_accelerator(even_batches=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : str = torch.nn.Linear(1 , 1 )
SCREAMING_SNAKE_CASE__ : str = accelerator.prepare(__lowerCAmelCase )
create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 )
with warnings.catch_warnings():
warnings.filterwarnings("""ignore""" )
try:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ):
SCREAMING_SNAKE_CASE__ : Any = batch_dl.batch_sampler.even_batches
except AttributeError:
# ensure attribute error is not raised when processing iterable dl
raise AssertionError
assert batch_dl_overridden_value == overridden_even_batches
assert batch_dl.batch_sampler.even_batches == default_even_batches
def _lowercase ( ) -> List[str]:
SCREAMING_SNAKE_CASE__ : str = create_accelerator()
SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.nn.Linear(1 , 1 )
SCREAMING_SNAKE_CASE__ : Optional[int] = accelerator.prepare(__lowerCAmelCase )
create_dataloader(__lowerCAmelCase , dataset_size=3 , batch_size=1 , iterable=__lowerCAmelCase )
with warnings.catch_warnings(record=__lowerCAmelCase ) as w:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=__lowerCAmelCase ):
pass
assert issubclass(w[-1].category , __lowerCAmelCase )
assert "only supported for map-style datasets" in str(w[-1].message )
def _lowercase ( ) -> Dict:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = create_accelerator()
accelerator.print("""Test that even_batches variable ensures uniform batches across processes""" )
test_default_ensures_even_batch_sizes()
accelerator.print("""Run tests with even_batches disabled""" )
test_can_disable_even_batches()
accelerator.print("""Test joining uneven inputs""" )
test_can_join_uneven_inputs()
accelerator.print("""Test overriding even_batches when joining uneven inputs""" )
test_join_can_override_even_batches()
accelerator.print("""Test overriding even_batches for mixed dataloader types""" )
test_join_can_override_for_mixed_type_dataloaders()
accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders""" )
test_join_raises_warning_for_iterable_when_overriding_even_batches()
accelerator.print("""Test join with non DDP distributed raises warning""" )
SCREAMING_SNAKE_CASE__ : Dict = accelerator.state.distributed_type
SCREAMING_SNAKE_CASE__ : Optional[int] = DistributedType.FSDP
test_join_raises_warning_for_non_ddp_distributed(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : str = original_state
if __name__ == "__main__":
main()
| 680 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__UpperCAmelCase :str = {
"configuration_efficientnet": [
"EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP",
"EfficientNetConfig",
"EfficientNetOnnxConfig",
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase :str = ["EfficientNetImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase :List[Any] = [
"EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"EfficientNetForImageClassification",
"EfficientNetModel",
"EfficientNetPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_efficientnet import (
EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
EfficientNetConfig,
EfficientNetOnnxConfig,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_efficientnet import EfficientNetImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_efficientnet import (
EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
EfficientNetForImageClassification,
EfficientNetModel,
EfficientNetPreTrainedModel,
)
else:
import sys
__UpperCAmelCase :int = _LazyModule(__name__, globals()["__file__"], _import_structure) | 702 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True)
os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True)
os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True)
def _a ( _lowercase : Any ):
'''simple docstring'''
if hor == 128:
__UpperCAmelCase : Optional[Any] = ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''')
__UpperCAmelCase : Union[str, Any] = (32, 128, 256)
__UpperCAmelCase : str = ('''UpResnetBlock1D''', '''UpResnetBlock1D''')
elif hor == 32:
__UpperCAmelCase : Optional[Any] = ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''')
__UpperCAmelCase : Any = (32, 64, 128, 256)
__UpperCAmelCase : Optional[int] = ('''UpResnetBlock1D''', '''UpResnetBlock1D''', '''UpResnetBlock1D''')
__UpperCAmelCase : Any = torch.load(F'/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch' )
__UpperCAmelCase : str = model.state_dict()
__UpperCAmelCase : int = {
'''down_block_types''': down_block_types,
'''block_out_channels''': block_out_channels,
'''up_block_types''': up_block_types,
'''layers_per_block''': 1,
'''use_timestep_embedding''': True,
'''out_block_type''': '''OutConv1DBlock''',
'''norm_num_groups''': 8,
'''downsample_each_block''': False,
'''in_channels''': 14,
'''out_channels''': 14,
'''extra_in_channels''': 0,
'''time_embedding_type''': '''positional''',
'''flip_sin_to_cos''': False,
'''freq_shift''': 1,
'''sample_size''': 65536,
'''mid_block_type''': '''MidResTemporalBlock1D''',
'''act_fn''': '''mish''',
}
__UpperCAmelCase : Optional[Any] = UNetaDModel(**_lowercase )
print(F'length of state dict: {len(state_dict.keys() )}' )
print(F'length of value function dict: {len(hf_value_function.state_dict().keys() )}' )
__UpperCAmelCase : Union[str, Any] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__UpperCAmelCase : List[Any] = state_dict.pop(_lowercase )
hf_value_function.load_state_dict(_lowercase )
torch.save(hf_value_function.state_dict() , F'hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin' )
with open(F'hub/hopper-medium-v2/unet/hor{hor}/config.json' , '''w''' ) as f:
json.dump(_lowercase , _lowercase )
def _a ( ):
'''simple docstring'''
__UpperCAmelCase : str = {
'''in_channels''': 14,
'''down_block_types''': ('''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''),
'''up_block_types''': (),
'''out_block_type''': '''ValueFunction''',
'''mid_block_type''': '''ValueFunctionMidBlock1D''',
'''block_out_channels''': (32, 64, 128, 256),
'''layers_per_block''': 1,
'''downsample_each_block''': True,
'''sample_size''': 65536,
'''out_channels''': 14,
'''extra_in_channels''': 0,
'''time_embedding_type''': '''positional''',
'''use_timestep_embedding''': True,
'''flip_sin_to_cos''': False,
'''freq_shift''': 1,
'''norm_num_groups''': 8,
'''act_fn''': '''mish''',
}
__UpperCAmelCase : str = torch.load('''/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch''' )
__UpperCAmelCase : Optional[Any] = model
__UpperCAmelCase : Optional[int] = UNetaDModel(**_lowercase )
print(F'length of state dict: {len(state_dict.keys() )}' )
print(F'length of value function dict: {len(hf_value_function.state_dict().keys() )}' )
__UpperCAmelCase : Union[str, Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__UpperCAmelCase : Dict = state_dict.pop(_lowercase )
hf_value_function.load_state_dict(_lowercase )
torch.save(hf_value_function.state_dict() , '''hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin''' )
with open('''hub/hopper-medium-v2/value_function/config.json''' , '''w''' ) as f:
json.dump(_lowercase , _lowercase )
if __name__ == "__main__":
unet(3_2)
# unet(128)
value_function() | 266 | 0 |
from __future__ import annotations
def lowerCAmelCase_ ( lowerCamelCase ):
__magic_name__ : int =0.0_0
__magic_name__ : Tuple =0
for resistor in resistors:
if resistor <= 0:
__magic_name__ : Optional[int] =F"Resistor at index {index} has a negative or zero value!"
raise ValueError(lowerCamelCase )
first_sum += 1 / float(lowerCamelCase )
index += 1
return 1 / first_sum
def lowerCAmelCase_ ( lowerCamelCase ):
__magic_name__ : Optional[int] =0.0_0
__magic_name__ : Optional[Any] =0
for resistor in resistors:
sum_r += resistor
if resistor < 0:
__magic_name__ : Optional[int] =F"Resistor at index {index} has a negative value!"
raise ValueError(lowerCamelCase )
index += 1
return sum_r
if __name__ == "__main__":
import doctest
doctest.testmod()
| 21 |
'''simple docstring'''
import inspect
import unittest
from transformers import DecisionTransformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import DecisionTransformerModel
from transformers.models.decision_transformer.modeling_decision_transformer import (
DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
class __magic_name__ :
def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=6 , snake_case_=17 , snake_case_=23 , snake_case_=11 , snake_case_=True , ):
lowercase =parent
lowercase =batch_size
lowercase =seq_length
lowercase =act_dim
lowercase =state_dim
lowercase =hidden_size
lowercase =max_length
lowercase =is_training
def _A( self ):
lowercase =floats_tensor((self.batch_size, self.seq_length, self.state_dim) )
lowercase =floats_tensor((self.batch_size, self.seq_length, self.act_dim) )
lowercase =floats_tensor((self.batch_size, self.seq_length, 1) )
lowercase =floats_tensor((self.batch_size, self.seq_length, 1) )
lowercase =ids_tensor((self.batch_size, self.seq_length) , vocab_size=10_00 )
lowercase =random_attention_mask((self.batch_size, self.seq_length) )
lowercase =self.get_config()
return (
config,
states,
actions,
rewards,
returns_to_go,
timesteps,
attention_mask,
)
def _A( self ):
return DecisionTransformerConfig(
batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , )
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , ):
lowercase =DecisionTransformerModel(config=snake_case_ )
model.to(snake_case_ )
model.eval()
lowercase =model(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ )
self.parent.assertEqual(result.state_preds.shape , states.shape )
self.parent.assertEqual(result.action_preds.shape , actions.shape )
self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions
def _A( self ):
lowercase =self.prepare_config_and_inputs()
(
(
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) ,
) =config_and_inputs
lowercase ={
'''states''': states,
'''actions''': actions,
'''rewards''': rewards,
'''returns_to_go''': returns_to_go,
'''timesteps''': timesteps,
'''attention_mask''': attention_mask,
}
return config, inputs_dict
@require_torch
class __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
UpperCamelCase__ = (DecisionTransformerModel,) if is_torch_available() else ()
UpperCamelCase__ = ()
UpperCamelCase__ = {'feature-extraction': DecisionTransformerModel} if is_torch_available() else {}
# Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
UpperCamelCase__ = False
# Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
UpperCamelCase__ = False
def _A( self ):
lowercase =DecisionTransformerModelTester(self )
lowercase =ConfigTester(self , config_class=snake_case_ , hidden_size=37 )
def _A( self ):
self.config_tester.run_common_tests()
def _A( self ):
lowercase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*snake_case_ )
@slow
def _A( self ):
for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase =DecisionTransformerModel.from_pretrained(snake_case_ )
self.assertIsNotNone(snake_case_ )
def _A( self ):
lowercase , lowercase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase =model_class(snake_case_ )
lowercase =inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase =[*signature.parameters.keys()]
lowercase =[
'''states''',
'''actions''',
'''rewards''',
'''returns_to_go''',
'''timesteps''',
'''attention_mask''',
]
self.assertListEqual(arg_names[: len(snake_case_ )] , snake_case_ )
@require_torch
class __magic_name__ ( unittest.TestCase ):
@slow
def _A( self ):
lowercase =2 # number of steps of autoregressive prediction we will perform
lowercase =10 # defined by the RL environment, may be normalized
lowercase =DecisionTransformerModel.from_pretrained('''edbeeching/decision-transformer-gym-hopper-expert''' )
lowercase =model.to(snake_case_ )
lowercase =model.config
torch.manual_seed(0 )
lowercase =torch.randn(1 , 1 , config.state_dim ).to(device=snake_case_ , dtype=torch.floataa ) # env.reset()
lowercase =torch.tensor(
[[0.24_27_93, -0.28_69_30_74, 0.8_74_26_13], [0.67_81_52_74, -0.08_10_10_85, -0.12_95_21_47]] , device=snake_case_ )
lowercase =torch.tensor(snake_case_ , device=snake_case_ , dtype=torch.floataa ).reshape(1 , 1 , 1 )
lowercase =state
lowercase =torch.zeros(1 , 0 , config.act_dim , device=snake_case_ , dtype=torch.floataa )
lowercase =torch.zeros(1 , 0 , device=snake_case_ , dtype=torch.floataa )
lowercase =torch.tensor(0 , device=snake_case_ , dtype=torch.long ).reshape(1 , 1 )
for step in range(snake_case_ ):
lowercase =torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=snake_case_ )] , dim=1 )
lowercase =torch.cat([rewards, torch.zeros(1 , 1 , device=snake_case_ )] , dim=1 )
lowercase =torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device )
with torch.no_grad():
lowercase , lowercase , lowercase =model(
states=snake_case_ , actions=snake_case_ , rewards=snake_case_ , returns_to_go=snake_case_ , timesteps=snake_case_ , attention_mask=snake_case_ , return_dict=snake_case_ , )
self.assertEqual(action_pred.shape , actions.shape )
self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) )
lowercase , lowercase , lowercase , lowercase =( # env.step(action)
torch.randn(1 , 1 , config.state_dim ).to(device=snake_case_ , dtype=torch.floataa ),
1.0,
False,
{},
)
lowercase =action_pred[0, -1]
lowercase =torch.cat([states, state] , dim=1 )
lowercase =returns_to_go[0, -1] - reward
lowercase =torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 )
lowercase =torch.cat(
[timesteps, torch.ones((1, 1) , device=snake_case_ , dtype=torch.long ) * (step + 1)] , dim=1 )
| 72 | 0 |
from collections import defaultdict
from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst
def __lowerCAmelCase ()-> List[str]:
"""simple docstring"""
snake_case_ , snake_case_ = 9, 14 # noqa: F841
snake_case_ = [
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[7, 8, 7],
[7, 6, 1],
[2, 8, 2],
[8, 6, 6],
[2, 3, 7],
[2, 5, 4],
[6, 5, 2],
[3, 5, 14],
[3, 4, 9],
[5, 4, 10],
[1, 7, 11],
]
snake_case_ = defaultdict(snake_case__ )
for nodea, nodea, cost in edges:
adjancency[nodea].append([nodea, cost] )
adjancency[nodea].append([nodea, cost] )
snake_case_ = mst(snake_case__ )
snake_case_ = [
[7, 6, 1],
[2, 8, 2],
[6, 5, 2],
[0, 1, 4],
[2, 5, 4],
[2, 3, 7],
[0, 7, 8],
[3, 4, 9],
]
for answer in expected:
snake_case_ = tuple(answer[:2] )
snake_case_ = tuple(edge[::-1] )
assert edge in result or reverse in result | 717 |
import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter
from transformers import HfArgumentParser
def __lowerCAmelCase (SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None )-> Tuple:
"""simple docstring"""
return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE )
@dataclass
class lowerCAmelCase_ :
'''simple docstring'''
__snake_case = field(
metadata={"help": "The csv file to plot."} , )
__snake_case = field(
default=lowerCamelCase__ , metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."} , )
__snake_case = field(
default=lowerCamelCase__ , metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."} , )
__snake_case = field(
default=lowerCamelCase__ , metadata={"help": "Disable logarithmic scale when plotting"} , )
__snake_case = field(
default=lowerCamelCase__ , metadata={
"help": "Whether the csv file has training results or inference results. Defaults to inference results."
} , )
__snake_case = field(
default=lowerCamelCase__ , metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."} , )
__snake_case = list_field(
default=lowerCamelCase__ , metadata={"help": "List of model names that are used instead of the ones in the csv file."} )
def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Optional[Any]:
"""simple docstring"""
try:
int(SCREAMING_SNAKE_CASE )
return True
except ValueError:
return False
def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Tuple:
"""simple docstring"""
try:
float(SCREAMING_SNAKE_CASE )
return True
except ValueError:
return False
class lowerCAmelCase_ :
'''simple docstring'''
def __init__( self , _UpperCAmelCase ):
snake_case_ = args
snake_case_ = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} )
with open(self.args.csv_file , newline='''''' ) as csv_file:
snake_case_ = csv.DictReader(_UpperCAmelCase )
for row in reader:
snake_case_ = row['''model''']
self.result_dict[model_name]["bsz"].append(int(row['''batch_size'''] ) )
self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length'''] ) )
if can_convert_to_int(row['''result'''] ):
# value is not None
snake_case_ = int(row['''result'''] )
elif can_convert_to_float(row['''result'''] ):
# value is not None
snake_case_ = float(row['''result'''] )
def UpperCamelCase__ ( self ):
snake_case_ , snake_case_ = plt.subplots()
snake_case_ = '''Time usage''' if self.args.is_time else '''Memory usage'''
snake_case_ = title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference'''
if not self.args.no_log_scale:
# set logarithm scales
ax.set_xscale('''log''' )
ax.set_yscale('''log''' )
for axis in [ax.xaxis, ax.yaxis]:
axis.set_major_formatter(ScalarFormatter() )
for model_name_idx, model_name in enumerate(self.result_dict.keys() ):
snake_case_ = sorted(set(self.result_dict[model_name]['''bsz'''] ) )
snake_case_ = sorted(set(self.result_dict[model_name]['''seq_len'''] ) )
snake_case_ = self.result_dict[model_name]['''result''']
((snake_case_) , (snake_case_)) = (
(batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
)
snake_case_ = (
model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
)
for inner_loop_value in inner_loop_array:
if self.args.plot_along_batch:
snake_case_ = np.asarray(
[results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=_UpperCAmelCase , )
else:
snake_case_ = np.asarray(
[results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , )
((snake_case_) , (snake_case_)) = (
('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''')
)
snake_case_ = np.asarray(_UpperCAmelCase , _UpperCAmelCase )[: len(_UpperCAmelCase )]
plt.scatter(
_UpperCAmelCase , _UpperCAmelCase , label=F'''{label_model_name} - {inner_loop_label}: {inner_loop_value}''' )
plt.plot(_UpperCAmelCase , _UpperCAmelCase , '''--''' )
title_str += F''' {label_model_name} vs.'''
snake_case_ = title_str[:-4]
snake_case_ = '''Time in s''' if self.args.is_time else '''Memory in MB'''
# plot
plt.title(_UpperCAmelCase )
plt.xlabel(_UpperCAmelCase )
plt.ylabel(_UpperCAmelCase )
plt.legend()
if self.args.figure_png_file is not None:
plt.savefig(self.args.figure_png_file )
else:
plt.show()
def __lowerCAmelCase ()-> int:
"""simple docstring"""
snake_case_ = HfArgumentParser(SCREAMING_SNAKE_CASE )
snake_case_ = parser.parse_args_into_dataclasses()[0]
snake_case_ = Plot(args=SCREAMING_SNAKE_CASE )
plot.plot()
if __name__ == "__main__":
main() | 531 | 0 |
'''simple docstring'''
from jiwer import compute_measures
import datasets
_snake_case : Dict = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'
_snake_case : List[str] = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'
_snake_case : List[str] = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION )
class A ( datasets.Metric ):
def __lowerCAmelCase ( self : Tuple ) -> Dict:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' , id='''sequence''' ),
'''references''': datasets.Value('''string''' , id='''sequence''' ),
} ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[
'''https://en.wikipedia.org/wiki/Word_error_rate''',
] , )
def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : int=None , lowerCAmelCase_ : Optional[Any]=False ) -> str:
"""simple docstring"""
if concatenate_texts:
return compute_measures(lowerCAmelCase_ , lowerCAmelCase_ )["wer"]
else:
_a = 0
_a = 0
for prediction, reference in zip(lowerCAmelCase_ , lowerCAmelCase_ ):
_a = compute_measures(lowerCAmelCase_ , lowerCAmelCase_ )
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total
| 22 |
'''simple docstring'''
def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ):
a__ : List[str] = len(lowerCAmelCase__ )
a__ : int = [[0] * n for i in range(lowerCAmelCase__ )]
for i in range(lowerCAmelCase__ ):
a__ : Dict = y_points[i]
for i in range(2 , lowerCAmelCase__ ):
for j in range(lowerCAmelCase__ , lowerCAmelCase__ ):
a__ : Any = (
(xa - x_points[j - i + 1]) * q[j][i - 1]
- (xa - x_points[j]) * q[j - 1][i - 1]
) / (x_points[j] - x_points[j - i + 1])
return [q[n - 1][n - 1], q]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 688 | 0 |
'''simple docstring'''
import json
import os
import tempfile
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ImageGPTImageProcessor
class _SCREAMING_SNAKE_CASE (unittest.TestCase ):
def __init__( self : List[Any] , __UpperCamelCase : int , __UpperCamelCase : Optional[Any]=7 , __UpperCamelCase : Any=3 , __UpperCamelCase : Dict=18 , __UpperCamelCase : Optional[Any]=30 , __UpperCamelCase : Any=400 , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : Optional[int]=None , __UpperCamelCase : Optional[Any]=True , ) -> Dict:
"""simple docstring"""
snake_case__ : Dict = size if size is not None else {'''height''': 18, '''width''': 18}
snake_case__ : int = parent
snake_case__ : Union[str, Any] = batch_size
snake_case__ : Tuple = num_channels
snake_case__ : int = image_size
snake_case__ : List[Any] = min_resolution
snake_case__ : int = max_resolution
snake_case__ : Tuple = do_resize
snake_case__ : List[Any] = size
snake_case__ : Dict = do_normalize
def lowerCAmelCase ( self : Any ) -> Dict:
"""simple docstring"""
return {
# here we create 2 clusters for the sake of simplicity
"clusters": np.asarray(
[
[0.8866443634033203, 0.6618829369544983, 0.3891746401786804],
[-0.6042559146881104, -0.02295008860528469, 0.5423797369003296],
] ),
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
}
@require_torch
@require_vision
class _SCREAMING_SNAKE_CASE (lowerCAmelCase__, unittest.TestCase ):
A__ = ImageGPTImageProcessor if is_vision_available() else None
def lowerCAmelCase ( self : Optional[Any] ) -> str:
"""simple docstring"""
snake_case__ : Optional[int] = ImageGPTImageProcessingTester(self )
@property
def lowerCAmelCase ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase ( self : Union[str, Any] ) -> int:
"""simple docstring"""
snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , '''clusters''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) )
def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
snake_case__ : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} )
snake_case__ : Tuple = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} )
def lowerCAmelCase ( self : List[str] ) -> int:
"""simple docstring"""
snake_case__ : int = self.image_processing_class(**self.image_processor_dict )
snake_case__ : List[Any] = json.loads(image_processor.to_json_string() )
for key, value in self.image_processor_dict.items():
if key == "clusters":
self.assertTrue(np.array_equal(_lowerCamelCase , obj[key] ) )
else:
self.assertEqual(obj[key] , _lowerCamelCase )
def lowerCAmelCase ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
snake_case__ : Tuple = self.image_processing_class(**self.image_processor_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
snake_case__ : Optional[Any] = os.path.join(_lowerCamelCase , '''image_processor.json''' )
image_processor_first.to_json_file(_lowerCamelCase )
snake_case__ : int = self.image_processing_class.from_json_file(_lowerCamelCase ).to_dict()
snake_case__ : int = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(_lowerCamelCase , image_processor_second[key] ) )
else:
self.assertEqual(image_processor_first[key] , _lowerCamelCase )
def lowerCAmelCase ( self : Dict ) -> Optional[Any]:
"""simple docstring"""
snake_case__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
image_processor_first.save_pretrained(_lowerCamelCase )
snake_case__ : Tuple = self.image_processing_class.from_pretrained(_lowerCamelCase ).to_dict()
snake_case__ : Tuple = image_processor_first.to_dict()
for key, value in image_processor_first.items():
if key == "clusters":
self.assertTrue(np.array_equal(_lowerCamelCase , image_processor_second[key] ) )
else:
self.assertEqual(image_processor_first[key] , _lowerCamelCase )
@unittest.skip('''ImageGPT requires clusters at initialization''' )
def lowerCAmelCase ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
pass
def __UpperCAmelCase ( ) -> Optional[Any]:
snake_case__ : Any = load_dataset('''hf-internal-testing/fixtures_image_utils''' , split='''test''' )
snake_case__ : Dict = Image.open(dataset[4]['''file'''] )
snake_case__ : Optional[int] = Image.open(dataset[5]['''file'''] )
snake_case__ : Union[str, Any] = [imagea, imagea]
return images
@require_vision
@require_torch
class _SCREAMING_SNAKE_CASE (unittest.TestCase ):
@slow
def lowerCAmelCase ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
snake_case__ : Any = ImageGPTImageProcessor.from_pretrained('''openai/imagegpt-small''' )
snake_case__ : Optional[Any] = prepare_images()
# test non-batched
snake_case__ : int = image_processing(images[0] , return_tensors='''pt''' )
self.assertIsInstance(encoding.input_ids , torch.LongTensor )
self.assertEqual(encoding.input_ids.shape , (1, 1024) )
snake_case__ : Any = [306, 191, 191]
self.assertEqual(encoding.input_ids[0, :3].tolist() , _lowerCamelCase )
# test batched
snake_case__ : Any = image_processing(_lowerCamelCase , return_tensors='''pt''' )
self.assertIsInstance(encoding.input_ids , torch.LongTensor )
self.assertEqual(encoding.input_ids.shape , (2, 1024) )
snake_case__ : Optional[Any] = [303, 13, 13]
self.assertEqual(encoding.input_ids[1, -3:].tolist() , _lowerCamelCase )
| 712 |
'''simple docstring'''
def __UpperCAmelCase ( UpperCamelCase__ :int ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 574 | 0 |
def __UpperCAmelCase ( __a : Optional[Any] ) -> Any:
"""simple docstring"""
_a : List[str] = [0] * len(__a )
_a : Union[str, Any] = []
_a : Dict = [1] * len(__a )
for values in graph.values():
for i in values:
indegree[i] += 1
for i in range(len(__a ) ):
if indegree[i] == 0:
queue.append(__a )
while queue:
_a : Optional[int] = queue.pop(0 )
for x in graph[vertex]:
indegree[x] -= 1
if long_dist[vertex] + 1 > long_dist[x]:
_a : int = long_dist[vertex] + 1
if indegree[x] == 0:
queue.append(__a )
print(max(__a ) )
# Adjacency list of Graph
a__ = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
longest_distance(graph)
| 14 | '''simple docstring'''
class _lowercase :
'''simple docstring'''
def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> None:
__lowerCAmelCase = size
__lowerCAmelCase = [0] * size
__lowerCAmelCase = [0] * size
@staticmethod
def a ( SCREAMING_SNAKE_CASE__ : int ) -> int:
return index | (index + 1)
@staticmethod
def a ( SCREAMING_SNAKE_CASE__ : int ) -> int:
return (index & (index + 1)) - 1
def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None:
__lowerCAmelCase = value
while index < self.size:
__lowerCAmelCase = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1
if current_left_border == index:
__lowerCAmelCase = value
else:
__lowerCAmelCase = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
__lowerCAmelCase = self.get_next(SCREAMING_SNAKE_CASE__ )
def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int:
right -= 1 # Because of right is exclusive
__lowerCAmelCase = 0
while left <= right:
__lowerCAmelCase = self.get_prev(SCREAMING_SNAKE_CASE__ )
if left <= current_left:
__lowerCAmelCase = max(SCREAMING_SNAKE_CASE__ , self.tree[right] )
__lowerCAmelCase = current_left
else:
__lowerCAmelCase = max(SCREAMING_SNAKE_CASE__ , self.arr[right] )
right -= 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| 427 | 0 |
import os
from typing import BinaryIO, Optional, Union
import numpy as np
import pyarrow.parquet as pq
from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def snake_case (__lowercase ) -> Optional[int]:
'''simple docstring'''
_snake_case : Optional[int] = np.inf
def set_batch_size(__lowercase ) -> None:
nonlocal batch_size
if isinstance(__lowercase , __lowercase ):
_snake_case : Dict = min(__lowercase , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS )
elif isinstance(__lowercase , __lowercase ):
_snake_case : str = min(__lowercase , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS )
elif isinstance(__lowercase , __lowercase ) and feature.dtype == "binary":
_snake_case : Any = min(__lowercase , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS )
_visit(__lowercase , __lowercase )
return None if batch_size is np.inf else batch_size
class lowercase_ ( __snake_case ):
def __init__( self , lowercase_ , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = False , lowercase_ = False , lowercase_ = None , **lowercase_ , ):
super().__init__(
lowercase_ , split=lowercase_ , features=lowercase_ , cache_dir=lowercase_ , keep_in_memory=lowercase_ , streaming=lowercase_ , num_proc=lowercase_ , **lowercase_ , )
_snake_case : int = path_or_paths if isinstance(lowercase_ , lowercase_ ) else {self.split: path_or_paths}
_snake_case : Optional[int] = _PACKAGED_DATASETS_MODULES["parquet"][1]
_snake_case : Optional[Any] = Parquet(
cache_dir=lowercase_ , data_files=lowercase_ , features=lowercase_ , hash=lowercase_ , **lowercase_ , )
def UpperCamelCase ( self ):
# Build iterable dataset
if self.streaming:
_snake_case : List[str] = self.builder.as_streaming_dataset(split=self.split )
# Build regular (map-style) dataset
else:
_snake_case : Union[str, Any] = None
_snake_case : Optional[Any] = None
_snake_case : Any = None
_snake_case : Tuple = None
self.builder.download_and_prepare(
download_config=lowercase_ , download_mode=lowercase_ , verification_mode=lowercase_ , base_path=lowercase_ , num_proc=self.num_proc , )
_snake_case : int = self.builder.as_dataset(
split=self.split , verification_mode=lowercase_ , in_memory=self.keep_in_memory )
return dataset
class lowercase_ :
def __init__( self , lowercase_ , lowercase_ , lowercase_ = None , **lowercase_ , ):
_snake_case : Optional[int] = dataset
_snake_case : List[str] = path_or_buf
_snake_case : Optional[Any] = batch_size or get_writer_batch_size(dataset.features )
_snake_case : int = parquet_writer_kwargs
def UpperCamelCase ( self ):
_snake_case : Any = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE
if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ):
with open(self.path_or_buf , "wb+" ) as buffer:
_snake_case : Union[str, Any] = self._write(file_obj=lowercase_ , batch_size=lowercase_ , **self.parquet_writer_kwargs )
else:
_snake_case : int = self._write(file_obj=self.path_or_buf , batch_size=lowercase_ , **self.parquet_writer_kwargs )
return written
def UpperCamelCase ( self , lowercase_ , lowercase_ , **lowercase_ ):
_snake_case : List[str] = 0
_snake_case : List[Any] = parquet_writer_kwargs.pop("path_or_buf" , lowercase_ )
_snake_case : str = self.dataset.features.arrow_schema
_snake_case : Tuple = pq.ParquetWriter(lowercase_ , schema=lowercase_ , **lowercase_ )
for offset in logging.tqdm(
range(0 , len(self.dataset ) , lowercase_ ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating parquet from Arrow format" , ):
_snake_case : Dict = query_table(
table=self.dataset._data , key=slice(lowercase_ , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , )
writer.write_table(lowercase_ )
written += batch.nbytes
writer.close()
return written | 580 | import itertools
from dataclasses import dataclass
from typing import Optional
import pandas as pd
import pyarrow as pa
import datasets
from datasets.table import table_cast
@dataclass
class lowercase_ ( datasets.BuilderConfig ):
_lowerCamelCase = None
class lowercase_ ( datasets.ArrowBasedBuilder ):
_lowerCamelCase = PandasConfig
def UpperCamelCase ( self ):
return datasets.DatasetInfo(features=self.config.features )
def UpperCamelCase ( self , lowercase_ ):
if not self.config.data_files:
raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""" )
_snake_case : Any = dl_manager.download_and_extract(self.config.data_files )
if isinstance(lowercase_ , (str, list, tuple) ):
_snake_case : str = data_files
if isinstance(lowercase_ , lowercase_ ):
_snake_case : int = [files]
# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
_snake_case : Optional[Any] = [dl_manager.iter_files(lowercase_ ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )]
_snake_case : Optional[Any] = []
for split_name, files in data_files.items():
if isinstance(lowercase_ , lowercase_ ):
_snake_case : Tuple = [files]
# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
_snake_case : int = [dl_manager.iter_files(lowercase_ ) for file in files]
splits.append(datasets.SplitGenerator(name=lowercase_ , gen_kwargs={"files": files} ) )
return splits
def UpperCamelCase ( self , lowercase_ ):
if self.config.features is not None:
# more expensive cast to support nested features with keys in a different order
# allows str <-> int/float or str to Audio for example
_snake_case : str = table_cast(lowercase_ , self.config.features.arrow_schema )
return pa_table
def UpperCamelCase ( self , lowercase_ ):
for i, file in enumerate(itertools.chain.from_iterable(lowercase_ ) ):
with open(lowercase_ , "rb" ) as f:
_snake_case : Dict = pa.Table.from_pandas(pd.read_pickle(lowercase_ ) )
yield i, self._cast_table(lowercase_ ) | 580 | 1 |
__lowerCAmelCase : Tuple ='\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
__lowerCAmelCase : Optional[int] =[{'type': 'code', 'content': INSTALL_CONTENT}]
__lowerCAmelCase : Union[str, Any] ={
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 696 |
'''simple docstring'''
import re
from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P
# Sentinels
__lowerCAmelCase = object()
# For specifying empty leaf dict `{}`
__lowerCAmelCase = object()
def _UpperCAmelCase ( __A : List[str] , __A : Tuple ):
a_ : List[Any] = tuple((re.compile(x + '''$''' ) for x in qs) )
for i in range(len(__A ) - len(__A ) + 1 ):
a_ : Union[str, Any] = [x.match(__A ) for x, y in zip(__A , ks[i:] )]
if matches and all(__A ):
return True
return False
def _UpperCAmelCase ( __A : List[str] ):
def replace(__A : int , __A : Union[str, Any] ):
for rule, replacement in rules:
if _match(__A , __A ):
return replacement
return val
return replace
def _UpperCAmelCase ( ):
return [
# embeddings
(("transformer", "wpe", "embedding"), P('''mp''' , __A )),
(("transformer", "wte", "embedding"), P('''mp''' , __A )),
# atention
(("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(__A , '''mp''' )),
(("attention", "out_proj", "kernel"), P('''mp''' , __A )),
(("attention", "out_proj", "bias"), None),
# mlp
(("mlp", "c_fc", "kernel"), P(__A , '''mp''' )),
(("mlp", "c_fc", "bias"), P('''mp''' )),
(("mlp", "c_proj", "kernel"), P('''mp''' , __A )),
(("mlp", "c_proj", "bias"), None),
# layer norms
((r"ln_\d+", "bias"), None),
((r"\d+", r"ln_\d+", "scale"), None),
(("ln_f", "bias"), None),
(("ln_f", "scale"), None),
]
def _UpperCAmelCase ( __A : Union[str, Any] ):
a_ : Tuple = _get_partition_rules()
a_ : Tuple = _replacement_rules(__A )
a_ : Optional[Any] = {k: _unmatched for k in flatten_dict(__A )}
a_ : Optional[Any] = {k: replace(__A , __A ) for k, v in initd.items()}
assert _unmatched not in result.values(), "Incomplete partition spec."
return freeze(unflatten_dict(__A ) )
| 466 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
snake_case_ : int = {
"configuration_transfo_xl": ["TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "TransfoXLConfig"],
"tokenization_transfo_xl": ["TransfoXLCorpus", "TransfoXLTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : List[Any] = [
"TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
"AdaptiveEmbedding",
"TransfoXLForSequenceClassification",
"TransfoXLLMHeadModel",
"TransfoXLModel",
"TransfoXLPreTrainedModel",
"load_tf_weights_in_transfo_xl",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Dict = [
"TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFAdaptiveEmbedding",
"TFTransfoXLForSequenceClassification",
"TFTransfoXLLMHeadModel",
"TFTransfoXLMainLayer",
"TFTransfoXLModel",
"TFTransfoXLPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig
from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_transfo_xl import (
TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
AdaptiveEmbedding,
TransfoXLForSequenceClassification,
TransfoXLLMHeadModel,
TransfoXLModel,
TransfoXLPreTrainedModel,
load_tf_weights_in_transfo_xl,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_transfo_xl import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAdaptiveEmbedding,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLMainLayer,
TFTransfoXLModel,
TFTransfoXLPreTrainedModel,
)
else:
import sys
snake_case_ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 701 |
# Copyright (c) 2021-, NVIDIA CORPORATION. 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.
####################################################################################################
#
# Note: If when running this conversion script you're getting an exception:
# ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#
import argparse
import os
import re
import zipfile
import torch
from transformers import AutoTokenizer, GPTaConfig
def __a ( __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any]=0 ) -> Tuple:
"""simple docstring"""
if name is None:
lowerCamelCase_ : Dict = None
else:
lowerCamelCase_ : Any = "." * max(0 , spaces - 2 ) + "# {:" + str(50 - spaces ) + "s}"
lowerCamelCase_ : Dict = fmt.format(__UpperCAmelCase )
# Print and recurse (if needed).
if isinstance(__UpperCAmelCase , __UpperCAmelCase ):
if msg is not None:
print(__UpperCAmelCase )
for k in val.keys():
recursive_print(__UpperCAmelCase , val[k] , spaces + 2 )
elif isinstance(__UpperCAmelCase , torch.Tensor ):
print(__UpperCAmelCase , ":" , val.size() )
else:
print(__UpperCAmelCase , ":" , __UpperCAmelCase )
def __a ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase_ : Tuple = param.size()
if checkpoint_version == 1.0:
# version 1.0 stores [num_heads * hidden_size * num_splits, :]
lowerCamelCase_ : Dict = (num_heads, hidden_size, num_splits) + input_shape[1:]
lowerCamelCase_ : Optional[Any] = param.view(*__UpperCAmelCase )
lowerCamelCase_ : Optional[Any] = param.transpose(0 , 2 )
lowerCamelCase_ : Any = param.transpose(1 , 2 ).contiguous()
elif checkpoint_version >= 2.0:
# other versions store [num_heads * num_splits * hidden_size, :]
lowerCamelCase_ : Optional[int] = (num_heads, num_splits, hidden_size) + input_shape[1:]
lowerCamelCase_ : Optional[Any] = param.view(*__UpperCAmelCase )
lowerCamelCase_ : Optional[int] = param.transpose(0 , 1 ).contiguous()
lowerCamelCase_ : Union[str, Any] = param.view(*__UpperCAmelCase )
return param
def __a ( __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] ) -> str:
"""simple docstring"""
lowerCamelCase_ : Tuple = {}
# old versions did not store training args
lowerCamelCase_ : Optional[Any] = input_state_dict.get("args" , __UpperCAmelCase )
if ds_args is not None:
# do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
# from pprint import pprint
# pprint(vars(ds_args))
lowerCamelCase_ : List[str] = ds_args.padded_vocab_size
lowerCamelCase_ : Optional[int] = ds_args.max_position_embeddings
lowerCamelCase_ : Union[str, Any] = ds_args.hidden_size
lowerCamelCase_ : Tuple = ds_args.num_layers
lowerCamelCase_ : List[str] = ds_args.num_attention_heads
lowerCamelCase_ : List[str] = ds_args.ffn_hidden_size
# pprint(config)
# The number of heads.
lowerCamelCase_ : List[Any] = config.n_head
# The hidden_size per head.
lowerCamelCase_ : Tuple = config.n_embd // config.n_head
# Megatron-LM checkpoint version
if "checkpoint_version" in input_state_dict.keys():
lowerCamelCase_ : Any = input_state_dict["checkpoint_version"]
else:
lowerCamelCase_ : int = 0.0
# The model.
lowerCamelCase_ : int = input_state_dict["model"]
# The language model.
lowerCamelCase_ : Dict = model["language_model"]
# The embeddings.
lowerCamelCase_ : Optional[int] = lm["embedding"]
# The word embeddings.
lowerCamelCase_ : Union[str, Any] = embeddings["word_embeddings"]["weight"]
# Truncate the embedding table to vocab_size rows.
lowerCamelCase_ : int = word_embeddings[: config.vocab_size, :]
lowerCamelCase_ : int = word_embeddings
# The position embeddings.
lowerCamelCase_ : List[str] = embeddings["position_embeddings"]["weight"]
# Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size]
lowerCamelCase_ : List[Any] = pos_embeddings.size(0 )
if n_positions != config.n_positions:
raise ValueError(
f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" )
# Store the position embeddings.
lowerCamelCase_ : Optional[int] = pos_embeddings
# The transformer.
lowerCamelCase_ : List[str] = lm["transformer"] if "transformer" in lm.keys() else lm["encoder"]
# The regex to extract layer names.
lowerCamelCase_ : Optional[int] = re.compile(R"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)" )
# The simple map of names for "automated" rules.
lowerCamelCase_ : Optional[Any] = {
"attention.dense": ".attn.c_proj.",
"self_attention.dense": ".attn.c_proj.",
"mlp.dense_h_to_4h": ".mlp.c_fc.",
"mlp.dense_4h_to_h": ".mlp.c_proj.",
}
# Extract the layers.
for key, val in transformer.items():
# Match the name.
lowerCamelCase_ : Optional[int] = layer_re.match(__UpperCAmelCase )
# Stop if that's not a layer
if m is None:
break
# The index of the layer.
lowerCamelCase_ : str = int(m.group(1 ) )
# The name of the operation.
lowerCamelCase_ : Optional[int] = m.group(2 )
# Is it a weight or a bias?
lowerCamelCase_ : int = m.group(3 )
# The name of the layer.
lowerCamelCase_ : Optional[Any] = f"transformer.h.{layer_idx}"
# For layernorm(s), simply store the layer norm.
if op_name.endswith("layernorm" ):
lowerCamelCase_ : Optional[int] = "ln_1" if op_name.startswith("input" ) else "ln_2"
lowerCamelCase_ : int = val
# Transpose the QKV matrix.
elif (
op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
) and weight_or_bias == "weight":
# Insert a tensor of 1x1xDxD bias.
lowerCamelCase_ : Union[str, Any] = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view(
1 , 1 , __UpperCAmelCase , __UpperCAmelCase )
lowerCamelCase_ : str = causal_mask
# Insert a "dummy" tensor for masked_bias.
lowerCamelCase_ : Any = torch.tensor(-1e4 , dtype=torch.floataa )
lowerCamelCase_ : Union[str, Any] = masked_bias
lowerCamelCase_ : Union[str, Any] = fix_query_key_value_ordering(__UpperCAmelCase , __UpperCAmelCase , 3 , __UpperCAmelCase , __UpperCAmelCase )
# Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
lowerCamelCase_ : Dict = out_val.transpose(0 , 1 ).contiguous()
# Store.
lowerCamelCase_ : Tuple = out_val
# Transpose the bias.
elif (
op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
) and weight_or_bias == "bias":
lowerCamelCase_ : Union[str, Any] = fix_query_key_value_ordering(__UpperCAmelCase , __UpperCAmelCase , 3 , __UpperCAmelCase , __UpperCAmelCase )
# Store. No change of shape.
lowerCamelCase_ : Dict = out_val
# Transpose the weights.
elif weight_or_bias == "weight":
lowerCamelCase_ : Union[str, Any] = megatron_to_transformers[op_name]
lowerCamelCase_ : int = val.transpose(0 , 1 )
# Copy the bias.
elif weight_or_bias == "bias":
lowerCamelCase_ : Optional[int] = megatron_to_transformers[op_name]
lowerCamelCase_ : Dict = val
# DEBUG.
assert config.n_layer == layer_idx + 1
# The final layernorm.
lowerCamelCase_ : List[Any] = transformer["final_layernorm.weight"]
lowerCamelCase_ : List[Any] = transformer["final_layernorm.bias"]
# For LM head, transformers' wants the matrix to weight embeddings.
lowerCamelCase_ : Union[str, Any] = word_embeddings
# It should be done!
return output_state_dict
def __a ( ) -> int:
"""simple docstring"""
lowerCamelCase_ : Optional[int] = argparse.ArgumentParser()
parser.add_argument("--print-checkpoint-structure" , action="store_true" )
parser.add_argument(
"path_to_checkpoint" , type=__UpperCAmelCase , help="Path to the checkpoint file (.zip archive or direct .pt file)" , )
parser.add_argument(
"--config_file" , default="" , type=__UpperCAmelCase , help="An optional config json file describing the pre-trained model." , )
lowerCamelCase_ : str = parser.parse_args()
# Extract the basename.
lowerCamelCase_ : Tuple = os.path.dirname(args.path_to_checkpoint )
# Load the model.
# the .zip is very optional, let's keep it for backward compatibility
print(f"Extracting PyTorch state dictionary from {args.path_to_checkpoint}" )
if args.path_to_checkpoint.endswith(".zip" ):
with zipfile.ZipFile(args.path_to_checkpoint , "r" ) as checkpoint:
with checkpoint.open("release/mp_rank_00/model_optim_rng.pt" ) as pytorch_dict:
lowerCamelCase_ : int = torch.load(__UpperCAmelCase , map_location="cpu" )
else:
lowerCamelCase_ : int = torch.load(args.path_to_checkpoint , map_location="cpu" )
lowerCamelCase_ : Any = input_state_dict.get("args" , __UpperCAmelCase )
# Read the config, or default to the model released by NVIDIA.
if args.config_file == "":
if ds_args is not None:
if ds_args.bias_gelu_fusion:
lowerCamelCase_ : Optional[int] = "gelu_fast"
elif ds_args.openai_gelu:
lowerCamelCase_ : List[str] = "gelu_new"
else:
lowerCamelCase_ : int = "gelu"
else:
# in the very early days this used to be "gelu_new"
lowerCamelCase_ : Any = "gelu_new"
# Spell out all parameters in case the defaults change.
lowerCamelCase_ : int = GPTaConfig(
vocab_size=50257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__UpperCAmelCase , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1e-5 , initializer_range=0.0_2 , summary_type="cls_index" , summary_use_proj=__UpperCAmelCase , summary_activation=__UpperCAmelCase , summary_proj_to_labels=__UpperCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__UpperCAmelCase , use_cache=__UpperCAmelCase , bos_token_id=50256 , eos_token_id=50256 , )
else:
lowerCamelCase_ : Dict = GPTaConfig.from_json_file(args.config_file )
lowerCamelCase_ : Tuple = ["GPT2LMHeadModel"]
# Convert.
print("Converting" )
lowerCamelCase_ : Dict = convert_megatron_checkpoint(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
# Print the structure of converted state dict.
if args.print_checkpoint_structure:
recursive_print(__UpperCAmelCase , __UpperCAmelCase )
# Add tokenizer class info to config
# see https://github.com/huggingface/transformers/issues/13906)
if ds_args is not None:
lowerCamelCase_ : List[Any] = ds_args.tokenizer_type
if tokenizer_type == "GPT2BPETokenizer":
lowerCamelCase_ : Union[str, Any] = "gpt2"
elif tokenizer_type == "PretrainedFromHF":
lowerCamelCase_ : Union[str, Any] = ds_args.tokenizer_name_or_path
else:
raise ValueError(f"Unrecognized tokenizer_type {tokenizer_type}" )
else:
lowerCamelCase_ : List[Any] = "gpt2"
lowerCamelCase_ : Optional[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase )
lowerCamelCase_ : Union[str, Any] = type(__UpperCAmelCase ).__name__
lowerCamelCase_ : Dict = tokenizer_class
# Store the config to file.
print("Saving config" )
config.save_pretrained(__UpperCAmelCase )
# Save tokenizer based on args
print(f"Adding {tokenizer_class} tokenizer files" )
tokenizer.save_pretrained(__UpperCAmelCase )
# Store the state_dict to file.
lowerCamelCase_ : List[str] = os.path.join(__UpperCAmelCase , "pytorch_model.bin" )
print(f"Saving checkpoint to \"{output_checkpoint_file}\"" )
torch.save(__UpperCAmelCase , __UpperCAmelCase )
####################################################################################################
if __name__ == "__main__":
main()
####################################################################################################
| 253 | 0 |
import gc
import math
import unittest
import torch
from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
enable_full_determinism()
class _UpperCAmelCase ( lowercase , lowercase , unittest.TestCase ):
lowerCamelCase_ : Dict = UNetaDModel
lowerCamelCase_ : List[Any] = """sample"""
@property
def _snake_case ( self : Dict):
SCREAMING_SNAKE_CASE_ :Dict = 4
SCREAMING_SNAKE_CASE_ :int = 3
SCREAMING_SNAKE_CASE_ :Any = (32, 32)
SCREAMING_SNAKE_CASE_ :int = floats_tensor((batch_size, num_channels) + sizes).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Tuple = torch.tensor([10]).to(UpperCAmelCase)
return {"sample": noise, "timestep": time_step}
@property
def _snake_case ( self : Any):
return (3, 32, 32)
@property
def _snake_case ( self : str):
return (3, 32, 32)
def _snake_case ( self : List[Any]):
SCREAMING_SNAKE_CASE_ :Optional[Any] = {
"block_out_channels": (32, 64),
"down_block_types": ("DownBlock2D", "AttnDownBlock2D"),
"up_block_types": ("AttnUpBlock2D", "UpBlock2D"),
"attention_head_dim": 3,
"out_channels": 3,
"in_channels": 3,
"layers_per_block": 2,
"sample_size": 32,
}
SCREAMING_SNAKE_CASE_ :Tuple = self.dummy_input
return init_dict, inputs_dict
class _UpperCAmelCase ( lowercase , lowercase , unittest.TestCase ):
lowerCamelCase_ : str = UNetaDModel
lowerCamelCase_ : str = """sample"""
@property
def _snake_case ( self : int):
SCREAMING_SNAKE_CASE_ :Dict = 4
SCREAMING_SNAKE_CASE_ :List[str] = 4
SCREAMING_SNAKE_CASE_ :Tuple = (32, 32)
SCREAMING_SNAKE_CASE_ :int = floats_tensor((batch_size, num_channels) + sizes).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :List[Any] = torch.tensor([10]).to(UpperCAmelCase)
return {"sample": noise, "timestep": time_step}
@property
def _snake_case ( self : Any):
return (4, 32, 32)
@property
def _snake_case ( self : int):
return (4, 32, 32)
def _snake_case ( self : Optional[int]):
SCREAMING_SNAKE_CASE_ :Any = {
"sample_size": 32,
"in_channels": 4,
"out_channels": 4,
"layers_per_block": 2,
"block_out_channels": (32, 64),
"attention_head_dim": 32,
"down_block_types": ("DownBlock2D", "DownBlock2D"),
"up_block_types": ("UpBlock2D", "UpBlock2D"),
}
SCREAMING_SNAKE_CASE_ :Any = self.dummy_input
return init_dict, inputs_dict
def _snake_case ( self : List[str]):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Optional[int] = UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update" , output_loading_info=UpperCAmelCase)
self.assertIsNotNone(UpperCAmelCase)
self.assertEqual(len(loading_info["missing_keys"]) , 0)
model.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Any = model(**self.dummy_input).sample
assert image is not None, "Make sure output is not None"
@unittest.skipIf(torch_device != "cuda" , "This test is supposed to run on GPU")
def _snake_case ( self : Dict):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :str = UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update" , output_loading_info=UpperCAmelCase)
model.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :List[Any] = model(**self.dummy_input).sample
assert image is not None, "Make sure output is not None"
@unittest.skipIf(torch_device != "cuda" , "This test is supposed to run on GPU")
def _snake_case ( self : List[Any]):
# by defautl model loading will use accelerate as `low_cpu_mem_usage=True`
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :int = UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update" , output_loading_info=UpperCAmelCase)
model_accelerate.to(UpperCAmelCase)
model_accelerate.eval()
SCREAMING_SNAKE_CASE_ :Dict = torch.randn(
1 , model_accelerate.config.in_channels , model_accelerate.config.sample_size , model_accelerate.config.sample_size , generator=torch.manual_seed(0) , )
SCREAMING_SNAKE_CASE_ :Union[str, Any] = noise.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Optional[int] = torch.tensor([10] * noise.shape[0]).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Union[str, Any] = model_accelerate(UpperCAmelCase , UpperCAmelCase)["sample"]
# two models don't need to stay in the device at the same time
del model_accelerate
torch.cuda.empty_cache()
gc.collect()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :str = UNetaDModel.from_pretrained(
"fusing/unet-ldm-dummy-update" , output_loading_info=UpperCAmelCase , low_cpu_mem_usage=UpperCAmelCase)
model_normal_load.to(UpperCAmelCase)
model_normal_load.eval()
SCREAMING_SNAKE_CASE_ :List[Any] = model_normal_load(UpperCAmelCase , UpperCAmelCase)["sample"]
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , rtol=1E-3)
def _snake_case ( self : int):
SCREAMING_SNAKE_CASE_ :Optional[Any] = UNetaDModel.from_pretrained("fusing/unet-ldm-dummy-update")
model.eval()
model.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :List[Any] = torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0) , )
SCREAMING_SNAKE_CASE_ :int = noise.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :List[str] = torch.tensor([10] * noise.shape[0]).to(UpperCAmelCase)
with torch.no_grad():
SCREAMING_SNAKE_CASE_ :List[Any] = model(UpperCAmelCase , UpperCAmelCase).sample
SCREAMING_SNAKE_CASE_ :Tuple = output[0, -1, -3:, -3:].flatten().cpu()
# fmt: off
SCREAMING_SNAKE_CASE_ :Union[str, Any] = torch.tensor([-13.3258, -20.1100, -15.9873, -17.6617, -23.0596, -17.9419, -13.3675, -16.1889, -12.3800])
# fmt: on
self.assertTrue(torch_all_close(UpperCAmelCase , UpperCAmelCase , rtol=1E-3))
class _UpperCAmelCase ( lowercase , lowercase , unittest.TestCase ):
lowerCamelCase_ : Tuple = UNetaDModel
lowerCamelCase_ : List[str] = """sample"""
@property
def _snake_case ( self : List[str] , UpperCAmelCase : Dict=(32, 32)):
SCREAMING_SNAKE_CASE_ :Union[str, Any] = 4
SCREAMING_SNAKE_CASE_ :List[Any] = 3
SCREAMING_SNAKE_CASE_ :int = floats_tensor((batch_size, num_channels) + sizes).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :str = torch.tensor(batch_size * [10]).to(dtype=torch.intaa , device=UpperCAmelCase)
return {"sample": noise, "timestep": time_step}
@property
def _snake_case ( self : Tuple):
return (3, 32, 32)
@property
def _snake_case ( self : Union[str, Any]):
return (3, 32, 32)
def _snake_case ( self : Any):
SCREAMING_SNAKE_CASE_ :int = {
"block_out_channels": [32, 64, 64, 64],
"in_channels": 3,
"layers_per_block": 1,
"out_channels": 3,
"time_embedding_type": "fourier",
"norm_eps": 1E-6,
"mid_block_scale_factor": math.sqrt(2.0),
"norm_num_groups": None,
"down_block_types": [
"SkipDownBlock2D",
"AttnSkipDownBlock2D",
"SkipDownBlock2D",
"SkipDownBlock2D",
],
"up_block_types": [
"SkipUpBlock2D",
"SkipUpBlock2D",
"AttnSkipUpBlock2D",
"SkipUpBlock2D",
],
}
SCREAMING_SNAKE_CASE_ :int = self.dummy_input
return init_dict, inputs_dict
@slow
def _snake_case ( self : Optional[Any]):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Optional[Any] = UNetaDModel.from_pretrained("google/ncsnpp-celebahq-256" , output_loading_info=UpperCAmelCase)
self.assertIsNotNone(UpperCAmelCase)
self.assertEqual(len(loading_info["missing_keys"]) , 0)
model.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Any = self.dummy_input
SCREAMING_SNAKE_CASE_ :str = floats_tensor((4, 3) + (2_56, 2_56)).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :List[str] = noise
SCREAMING_SNAKE_CASE_ :int = model(**UpperCAmelCase)
assert image is not None, "Make sure output is not None"
@slow
def _snake_case ( self : Optional[int]):
SCREAMING_SNAKE_CASE_ :Any = UNetaDModel.from_pretrained("google/ncsnpp-celebahq-256")
model.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Optional[int] = 4
SCREAMING_SNAKE_CASE_ :List[str] = 3
SCREAMING_SNAKE_CASE_ :str = (2_56, 2_56)
SCREAMING_SNAKE_CASE_ :str = torch.ones((batch_size, num_channels) + sizes).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Tuple = torch.tensor(batch_size * [1E-4]).to(UpperCAmelCase)
with torch.no_grad():
SCREAMING_SNAKE_CASE_ :List[str] = model(UpperCAmelCase , UpperCAmelCase).sample
SCREAMING_SNAKE_CASE_ :List[Any] = output[0, -3:, -3:, -1].flatten().cpu()
# fmt: off
SCREAMING_SNAKE_CASE_ :Union[str, Any] = torch.tensor([-4842.8691, -6499.6631, -3800.1953, -7978.2686, -10980.7129, -20028.8535, 8148.2822, 2342.2905, 567.7608])
# fmt: on
self.assertTrue(torch_all_close(UpperCAmelCase , UpperCAmelCase , rtol=1E-2))
def _snake_case ( self : Tuple):
SCREAMING_SNAKE_CASE_ :Tuple = UNetaDModel.from_pretrained("fusing/ncsnpp-ffhq-ve-dummy-update")
model.to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Optional[int] = 4
SCREAMING_SNAKE_CASE_ :List[Any] = 3
SCREAMING_SNAKE_CASE_ :List[Any] = (32, 32)
SCREAMING_SNAKE_CASE_ :Tuple = torch.ones((batch_size, num_channels) + sizes).to(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Union[str, Any] = torch.tensor(batch_size * [1E-4]).to(UpperCAmelCase)
with torch.no_grad():
SCREAMING_SNAKE_CASE_ :int = model(UpperCAmelCase , UpperCAmelCase).sample
SCREAMING_SNAKE_CASE_ :int = output[0, -3:, -3:, -1].flatten().cpu()
# fmt: off
SCREAMING_SNAKE_CASE_ :str = torch.tensor([-0.0325, -0.0900, -0.0869, -0.0332, -0.0725, -0.0270, -0.0101, 0.0227, 0.0256])
# fmt: on
self.assertTrue(torch_all_close(UpperCAmelCase , UpperCAmelCase , rtol=1E-2))
def _snake_case ( self : Optional[Any]):
# not required for this model
pass
| 631 |
import argparse
import json
import os
import tensorstore as ts
import torch
from flax import serialization
from flax.traverse_util import flatten_dict, unflatten_dict
from tensorflow.io import gfile
from transformers.modeling_utils import dtype_byte_size
from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import (
rename_keys,
)
from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
from transformers.utils.hub import convert_file_size_to_int
def lowercase ( a , a ):
'''simple docstring'''
if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3:
# expert layer
SCREAMING_SNAKE_CASE_ :List[Any] = flax_key_tuple[:-1] + ("weight",)
SCREAMING_SNAKE_CASE_ :Any = torch.permute(a , (0, 2, 1) )
elif flax_key_tuple[-1] == "kernel" and ".".join(a ):
# linear layer
SCREAMING_SNAKE_CASE_ :str = flax_key_tuple[:-1] + ("weight",)
SCREAMING_SNAKE_CASE_ :Optional[int] = flax_tensor.T
elif flax_key_tuple[-1] in ["scale", "embedding"]:
SCREAMING_SNAKE_CASE_ :Union[str, Any] = flax_key_tuple[:-1] + ("weight",)
return flax_key_tuple, flax_tensor
def lowercase ( a , a , a ):
'''simple docstring'''
if "metadata" in layer:
SCREAMING_SNAKE_CASE_ :Dict = layer.split("metadata" )
SCREAMING_SNAKE_CASE_ :Optional[int] = "".join(split_layer[0] )[:-1]
SCREAMING_SNAKE_CASE_ :str = [tuple(("metadata" + split_layer[1]).split("/" ) )]
elif "kvstore" in layer:
SCREAMING_SNAKE_CASE_ :str = layer.split("kvstore" )
SCREAMING_SNAKE_CASE_ :str = "".join(split_layer[0] )[:-1]
SCREAMING_SNAKE_CASE_ :str = [tuple(("kvstore" + split_layer[1]).split("/" ) )]
else:
SCREAMING_SNAKE_CASE_ :Union[str, Any] = layer.split("/" )
SCREAMING_SNAKE_CASE_ :Optional[int] = "/".join(split_layer[:-1] )
SCREAMING_SNAKE_CASE_ :int = (split_layer[-1],)
if "kvstore/path" in layer:
SCREAMING_SNAKE_CASE_ :Union[str, Any] = F"{switch_checkpoint_path}/{checkpoint_info[layer]}"
elif "kvstore/driver" in layer:
SCREAMING_SNAKE_CASE_ :Tuple = "file"
else:
SCREAMING_SNAKE_CASE_ :str = checkpoint_info[layer]
return curr_real_layer_name, split_layer, content
def lowercase ( a , a ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :int = rename_keys(a )
SCREAMING_SNAKE_CASE_ :Union[str, Any] = {}
for k, v in current_block.items():
SCREAMING_SNAKE_CASE_ :List[str] = v
SCREAMING_SNAKE_CASE_ :Optional[Any] = new_current_block
torch.save(a , a )
def lowercase ( a , a , a , a , a = WEIGHTS_NAME ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :Optional[int] = convert_file_size_to_int(a )
SCREAMING_SNAKE_CASE_ :int = []
SCREAMING_SNAKE_CASE_ :str = {}
SCREAMING_SNAKE_CASE_ :List[str] = 0
SCREAMING_SNAKE_CASE_ :Optional[int] = 0
os.makedirs(a , exist_ok=a )
with gfile.GFile(switch_checkpoint_path + "/checkpoint" , "rb" ) as fp:
SCREAMING_SNAKE_CASE_ :int = serialization.msgpack_restore(fp.read() )["optimizer"]["target"]
SCREAMING_SNAKE_CASE_ :Any = flatten_dict(a , sep="/" )
SCREAMING_SNAKE_CASE_ :Optional[Any] = {}
for layer in checkpoint_info.keys():
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :List[Any] = get_key_and_tensorstore_dict(
a , a , a )
if curr_real_layer_name in all_layers:
SCREAMING_SNAKE_CASE_ :str = content
else:
SCREAMING_SNAKE_CASE_ :Optional[Any] = {split_layer[-1]: content}
for key in all_layers.keys():
# open tensorstore file
SCREAMING_SNAKE_CASE_ :Any = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result()
SCREAMING_SNAKE_CASE_ :List[Any] = torch.tensor(a )
SCREAMING_SNAKE_CASE_ :str = raw_weights.numel() * dtype_byte_size(raw_weights.dtype )
# use the renaming pattern from the small conversion scripts
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :Optional[Any] = rename_base_flax_keys(tuple(key.split("/" ) ) , a )
SCREAMING_SNAKE_CASE_ :Any = "/".join(a )
# If this weight is going to tip up over the maximal size, we split.
if current_block_size + weight_size > max_shard_size:
SCREAMING_SNAKE_CASE_ :str = os.path.join(
a , weights_name.replace(".bin" , F"-{len(a )+1:05d}-of-???.bin" ) )
rename_and_save_block(a , a )
sharded_state_dicts.append(current_block.keys() )
del current_block
SCREAMING_SNAKE_CASE_ :Tuple = {}
SCREAMING_SNAKE_CASE_ :Dict = 0
SCREAMING_SNAKE_CASE_ :Optional[int] = raw_weights.to(getattr(a , a ) )
current_block_size += weight_size
total_size += weight_size
# Add the last block
SCREAMING_SNAKE_CASE_ :Dict = os.path.join(a , weights_name.replace(".bin" , F"-{len(a )+1:05d}-of-???.bin" ) )
rename_and_save_block(a , a )
sharded_state_dicts.append(current_block.keys() )
# If we only have one shard, we return it
if len(a ) == 1:
return {weights_name: sharded_state_dicts[0]}, None
# Otherwise, let's build the index
SCREAMING_SNAKE_CASE_ :Optional[int] = {}
SCREAMING_SNAKE_CASE_ :int = {}
for idx, shard in enumerate(a ):
SCREAMING_SNAKE_CASE_ :Optional[Any] = weights_name.replace(
".bin" , F"-{idx+1:05d}-of-{len(a ):05d}.bin" ) # len(sharded_state_dicts):05d}
SCREAMING_SNAKE_CASE_ :Any = os.path.join(a , weights_name.replace(".bin" , F"-{idx+1:05d}-of-???.bin" ) )
os.rename(a , os.path.join(a , a ) )
SCREAMING_SNAKE_CASE_ :List[Any] = shard
for key in shard:
SCREAMING_SNAKE_CASE_ :str = shard_file
# Add the metadata
SCREAMING_SNAKE_CASE_ :List[str] = {"total_size": total_size}
SCREAMING_SNAKE_CASE_ :Optional[int] = {"metadata": metadata, "weight_map": weight_map}
with open(os.path.join(a , a ) , "w" , encoding="utf-8" ) as f:
SCREAMING_SNAKE_CASE_ :Optional[int] = json.dumps(a , indent=2 , sort_keys=a ) + "\n"
f.write(a )
return metadata, index
if __name__ == "__main__":
SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--switch_t5x_checkpoint_path",
default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600",
type=str,
required=False,
help="Path to a directory containing a folder per layer. Follows the original Google format.",
)
parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size")
parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model")
parser.add_argument(
"--pytorch_dump_folder_path",
default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted",
type=str,
required=False,
help="Path to the output pytorch model.",
)
SCREAMING_SNAKE_CASE__ = parser.parse_args()
shard_on_the_fly(
args.switch_tax_checkpoint_path,
args.pytorch_dump_folder_path,
args.max_shard_size,
args.dtype,
)
def lowercase ( ):
'''simple docstring'''
from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer
SCREAMING_SNAKE_CASE_ :Dict = SwitchTransformersConfig.from_pretrained("google/switch-base-8" )
config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" )
SCREAMING_SNAKE_CASE_ :str = SwitchTransformersForConditionalGeneration.from_pretrained(
"/home/arthur_huggingface_co/transformers/switch_converted" , device_map="auto" )
SCREAMING_SNAKE_CASE_ :List[Any] = TaTokenizer.from_pretrained("t5-small" )
SCREAMING_SNAKE_CASE_ :Optional[int] = "A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>."
SCREAMING_SNAKE_CASE_ :List[Any] = tokenizer(a , return_tensors="pt" ).input_ids
SCREAMING_SNAKE_CASE_ :List[str] = model.generate(a , decoder_start_token_id=0 )
print(tokenizer.decode(out[0] ) )
| 631 | 1 |
'''simple docstring'''
import argparse
import json
import subprocess
def lowerCamelCase_ ( lowercase__ , lowercase__):
lowerCamelCase__ = []
lowerCamelCase__ = (
F'''curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"'''
" https://api.github.com/repos/huggingface/transformers/actions/runners"
)
lowerCamelCase__ = subprocess.run(lowercase__ , shell=lowercase__ , stdout=subprocess.PIPE)
lowerCamelCase__ = output.stdout.decode("utf-8")
lowerCamelCase__ = json.loads(lowercase__)
lowerCamelCase__ = status["runners"]
for runner in runners:
if runner["name"] in target_runners:
if runner["status"] == "offline":
offline_runners.append(lowercase__)
# save the result so we can report them on Slack
with open("offline_runners.txt" , "w") as fp:
fp.write(json.dumps(lowercase__))
if len(lowercase__) > 0:
lowerCamelCase__ = "\n".join([x["name"] for x in offline_runners])
raise ValueError(F'''The following runners are offline:\n{failed}''')
if __name__ == "__main__":
def lowerCamelCase_ ( lowercase__):
return values.split(",")
__A : Dict = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--target_runners""",
default=None,
type=list_str,
required=True,
help="""Comma-separated list of runners to check status.""",
)
parser.add_argument(
"""--token""", default=None, type=str, required=True, help="""A token that has actions:read permission."""
)
__A : Optional[Any] = parser.parse_args()
get_runner_status(args.target_runners, args.token)
| 710 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
__A : Union[str, Any] = logging.get_logger(__name__)
__A : Tuple = {
"""EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class lowercase ( _lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = "gpt_neo"
lowerCAmelCase__ = ["past_key_values"]
lowerCAmelCase__ = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
def __init__( self : str , __lowerCamelCase : Optional[int]=50257 , __lowerCamelCase : Optional[int]=2048 , __lowerCamelCase : Optional[int]=2048 , __lowerCamelCase : Any=24 , __lowerCamelCase : List[Any]=[[["global", "local"], 12]] , __lowerCamelCase : Any=16 , __lowerCamelCase : Any=None , __lowerCamelCase : Optional[Any]=256 , __lowerCamelCase : List[Any]="gelu_new" , __lowerCamelCase : Any=0.0 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Union[str, Any]=0.0 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Dict=1E-5 , __lowerCamelCase : List[Any]=0.0_2 , __lowerCamelCase : List[Any]=True , __lowerCamelCase : Optional[int]=50256 , __lowerCamelCase : Tuple=50256 , **__lowerCamelCase : Optional[int] , ) -> str:
'''simple docstring'''
lowerCamelCase__ = vocab_size
lowerCamelCase__ = max_position_embeddings
lowerCamelCase__ = hidden_size
lowerCamelCase__ = num_layers
lowerCamelCase__ = num_heads
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = window_size
lowerCamelCase__ = activation_function
lowerCamelCase__ = resid_dropout
lowerCamelCase__ = embed_dropout
lowerCamelCase__ = attention_dropout
lowerCamelCase__ = classifier_dropout
lowerCamelCase__ = layer_norm_epsilon
lowerCamelCase__ = initializer_range
lowerCamelCase__ = use_cache
lowerCamelCase__ = bos_token_id
lowerCamelCase__ = eos_token_id
lowerCamelCase__ = attention_types
lowerCamelCase__ = self.expand_attention_types_params(__lowerCamelCase )
if len(self.attention_layers ) != self.num_layers:
raise ValueError(
"Configuration for convolutional module is incorrect. "
"It is required that `len(config.attention_layers)` == `config.num_layers` "
f'''but is `len(config.attention_layers) = {len(self.attention_layers )}`, '''
f'''`config.num_layers = {self.num_layers}`. '''
"`config.attention_layers` is prepared using `config.attention_types`. "
"Please verify the value of `config.attention_types` argument." )
super().__init__(bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
@staticmethod
def a__ ( __lowerCamelCase : int ) -> str:
'''simple docstring'''
lowerCamelCase__ = []
for item in attention_types:
for _ in range(item[1] ):
attentions.extend(item[0] )
return attentions
def lowerCamelCase_ ( lowercase__ , lowercase__ , lowercase__ , lowercase__):
import torch
lowerCamelCase__ = input.size()
lowerCamelCase__ = len(lowercase__)
lowerCamelCase__ = shape[dimension]
lowerCamelCase__ = torch.arange(0 , lowercase__ , lowercase__)
lowerCamelCase__ = torch.div(sizedim - size , lowercase__ , rounding_mode="floor") + 1
lowerCamelCase__ = torch.arange(lowercase__) + low_indices[:min_length][:, None]
lowerCamelCase__ = [slice(lowercase__)] * rank
lowerCamelCase__ = indices
lowerCamelCase__ = input[s]
lowerCamelCase__ = list(range(0 , rank + 1))
perm.append(perm.pop(dimension + 1))
return sliced.permute(lowercase__)
def lowerCamelCase_ ( lowercase__ , lowercase__):
import torch
lowerCamelCase__ = torch.arange(1 , lowercase__)
lowerCamelCase__ = torch.remainder(lowercase__ , lowercase__)
lowerCamelCase__ = remainders == 0
lowerCamelCase__ = candidates[divisor_indices]
lowerCamelCase__ = torch.max(lowercase__)
return largest_divisor, torch.div(lowercase__ , lowercase__ , rounding_mode="floor")
class lowercase ( _lowerCamelCase ):
'''simple docstring'''
@property
def a__ ( self : Any ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
lowerCamelCase__ = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} )
if self.use_past:
self.fill_with_past_key_values_(__lowerCamelCase , direction="inputs" )
lowerCamelCase__ = {0: "batch", 1: "past_sequence + sequence"}
else:
lowerCamelCase__ = {0: "batch", 1: "sequence"}
return common_inputs
@property
def a__ ( self : Any ) -> int:
'''simple docstring'''
return self._config.num_heads
def a__ ( self : Optional[Any] , __lowerCamelCase : PreTrainedTokenizer , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]:
'''simple docstring'''
lowerCamelCase__ = super(__lowerCamelCase , self ).generate_dummy_inputs(
__lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase )
# We need to order the input in the way they appears in the forward()
lowerCamelCase__ = OrderedDict({"input_ids": common_inputs["input_ids"]} )
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." )
else:
import torch
lowerCamelCase__ , lowerCamelCase__ = common_inputs["input_ids"].shape
# Not using the same length for past_key_values
lowerCamelCase__ = seqlen + 2
lowerCamelCase__ = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
lowerCamelCase__ = [
(torch.zeros(__lowerCamelCase ), torch.zeros(__lowerCamelCase )) for _ in range(self.num_layers )
]
lowerCamelCase__ = common_inputs["attention_mask"]
if self.use_past:
lowerCamelCase__ = ordered_inputs["attention_mask"].dtype
lowerCamelCase__ = torch.cat(
[ordered_inputs["attention_mask"], torch.ones(__lowerCamelCase , __lowerCamelCase , dtype=__lowerCamelCase )] , dim=1 )
return ordered_inputs
@property
def a__ ( self : Optional[Any] ) -> int:
'''simple docstring'''
return 13
| 187 | 0 |