code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.g4dn.xlarge""", """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.6, """eval_loss""": 0.9}, }, { """framework""": """tensorflow""", """script""": """run_tf.py""", """model_name_or_path""": """distilbert-base-cased""", """instance_type""": """ml.g4dn.xlarge""", """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.3, """eval_loss""": 0.9}, }, ] ) class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: Optional[int] ): if self.framework == "pytorch": subprocess.run( F'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding="""utf-8""" , check=UpperCamelCase__ , ) assert hasattr(self , """env""" ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: int=1 ): # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F'''{self.env.base_job_name}-single''' , instance_count=UpperCamelCase__ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase__ , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: int ): TrainingJobAnalytics(UpperCamelCase__ ).export_csv(F'''{self.env.test_path}/{job_name}_metrics.csv''' ) def lowerCamelCase_ ( self: int ): # create estimator lowerCamelCase__ : Union[str, Any] = self.create_estimator() # run training estimator.fit() # result dataframe lowerCamelCase__ : Any = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis lowerCamelCase__ : List[Any] = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] ) lowerCamelCase__ : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping lowerCamelCase__ : Any = ( Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""" , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy ) assert all(t <= self.results["""eval_loss"""] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'''{estimator.latest_training_job.name}.json''' , """w""" ) as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , UpperCamelCase__ )
631
'''simple docstring''' _A : List[str] ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
631
1
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class _lowercase : @property def lowerCamelCase_ ( self: Tuple ): return self.get_dummy_input() @property def lowerCamelCase_ ( self: Union[str, Any] ): if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.''' ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[Any]=True , UpperCamelCase__: Optional[Any]=False , UpperCamelCase__: List[Any]=False , UpperCamelCase__: Tuple=False , ): lowerCamelCase__ : List[Any] = 4 lowerCamelCase__ : int = 32 lowerCamelCase__ : List[Any] = (32, 32) lowerCamelCase__ : Dict = torch.manual_seed(0 ) lowerCamelCase__ : Union[str, Any] = torch.device(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = (batch_size, num_channels) + sizes lowerCamelCase__ : Any = randn_tensor(UpperCamelCase__ , generator=UpperCamelCase__ , device=UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = {"""hidden_states""": hidden_states} if include_temb: lowerCamelCase__ : Union[str, Any] = 128 lowerCamelCase__ : Optional[Any] = randn_tensor((batch_size, temb_channels) , generator=UpperCamelCase__ , device=UpperCamelCase__ ) if include_res_hidden_states_tuple: lowerCamelCase__ : Dict = torch.manual_seed(1 ) lowerCamelCase__ : Any = (randn_tensor(UpperCamelCase__ , generator=UpperCamelCase__ , device=UpperCamelCase__ ),) if include_encoder_hidden_states: lowerCamelCase__ : List[Any] = floats_tensor((batch_size, 32, 32) ).to(UpperCamelCase__ ) if include_skip_sample: lowerCamelCase__ : Optional[Any] = randn_tensor(((batch_size, 3) + sizes) , generator=UpperCamelCase__ , device=UpperCamelCase__ ) return dummy_input def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Any = { """in_channels""": 32, """out_channels""": 32, """temb_channels""": 128, } if self.block_type == "up": lowerCamelCase__ : str = 32 if self.block_type == "mid": init_dict.pop("""out_channels""" ) lowerCamelCase__ : Tuple = self.dummy_input return init_dict, inputs_dict def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Tuple ): lowerCamelCase__ , lowerCamelCase__ : int = self.prepare_init_args_and_inputs_for_common() lowerCamelCase__ : str = self.block_class(**UpperCamelCase__ ) unet_block.to(UpperCamelCase__ ) unet_block.eval() with torch.no_grad(): lowerCamelCase__ : int = unet_block(**UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Optional[int] = output[0] self.assertEqual(output.shape , self.output_shape ) lowerCamelCase__ : List[str] = output[0, -1, -3:, -3:] lowerCamelCase__ : Dict = torch.tensor(UpperCamelCase__ ).to(UpperCamelCase__ ) assert torch_all_close(output_slice.flatten() , UpperCamelCase__ , atol=5e-3 ) @unittest.skipIf(torch_device == """mps""" , """Training is not supported in mps""" ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ , lowerCamelCase__ : Tuple = self.prepare_init_args_and_inputs_for_common() lowerCamelCase__ : Union[str, Any] = self.block_class(**UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.train() lowerCamelCase__ : Optional[Any] = model(**UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : str = output[0] lowerCamelCase__ : Optional[int] = torch.device(UpperCamelCase__ ) lowerCamelCase__ : List[str] = randn_tensor(output.shape , device=UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = torch.nn.functional.mse_loss(UpperCamelCase__ , UpperCamelCase__ ) loss.backward()
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Any =logging.get_logger(__name__) _A : Dict ={ '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class _lowercase ( _lowercase ): a = """trocr""" a = ["""past_key_values"""] a = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Optional[Any] , UpperCamelCase__: int=50_265 , UpperCamelCase__: int=1_024 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Dict=16 , UpperCamelCase__: int=4_096 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: int=512 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Any=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: str=True , UpperCamelCase__: Tuple=False , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Tuple=True , UpperCamelCase__: Dict=1 , UpperCamelCase__: List[str]=0 , UpperCamelCase__: Union[str, Any]=2 , **UpperCamelCase__: str , ): lowerCamelCase__ : Any = vocab_size lowerCamelCase__ : Tuple = d_model lowerCamelCase__ : Any = decoder_layers lowerCamelCase__ : Dict = decoder_attention_heads lowerCamelCase__ : str = decoder_ffn_dim lowerCamelCase__ : Tuple = activation_function lowerCamelCase__ : Dict = max_position_embeddings lowerCamelCase__ : int = dropout lowerCamelCase__ : int = attention_dropout lowerCamelCase__ : List[Any] = activation_dropout lowerCamelCase__ : Union[str, Any] = init_std lowerCamelCase__ : Optional[int] = decoder_layerdrop lowerCamelCase__ : Dict = use_cache lowerCamelCase__ : Any = scale_embedding lowerCamelCase__ : Optional[int] = use_learned_position_embeddings lowerCamelCase__ : List[str] = layernorm_embedding super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
631
1
'''simple docstring''' from math import pi, sqrt, tan def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> float: if side_length < 0: raise ValueError("""surface_area_cube() only accepts non-negative values""" ) return 6 * side_length**2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> float: if length < 0 or breadth < 0 or height < 0: raise ValueError("""surface_area_cuboid() only accepts non-negative values""" ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> float: if radius < 0: raise ValueError("""surface_area_sphere() only accepts non-negative values""" ) return 4 * pi * radius**2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> float: if radius < 0: raise ValueError("""surface_area_hemisphere() only accepts non-negative values""" ) return 3 * pi * radius**2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if radius < 0 or height < 0: raise ValueError("""surface_area_cone() only accepts non-negative values""" ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> float: if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( """surface_area_conical_frustum() only accepts non-negative values""" ) lowerCamelCase__ : List[Any] = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if radius < 0 or height < 0: raise ValueError("""surface_area_cylinder() only accepts non-negative values""" ) return 2 * pi * radius * (height + radius) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if torus_radius < 0 or tube_radius < 0: raise ValueError("""surface_area_torus() only accepts non-negative values""" ) if torus_radius < tube_radius: raise ValueError( """surface_area_torus() does not support spindle or self intersecting tori""" ) return 4 * pow(UpperCamelCase , 2 ) * torus_radius * tube_radius def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if length < 0 or width < 0: raise ValueError("""area_rectangle() only accepts non-negative values""" ) return length * width def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> float: if side_length < 0: raise ValueError("""area_square() only accepts non-negative values""" ) return side_length**2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if base < 0 or height < 0: raise ValueError("""area_triangle() only accepts non-negative values""" ) return (base * height) / 2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> float: if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError("""area_triangle_three_sides() only accepts non-negative values""" ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError("""Given three sides do not form a triangle""" ) lowerCamelCase__ : Optional[int] = (sidea + sidea + sidea) / 2 lowerCamelCase__ : Optional[Any] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if base < 0 or height < 0: raise ValueError("""area_parallelogram() only accepts non-negative values""" ) return base * height def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> float: if basea < 0 or basea < 0 or height < 0: raise ValueError("""area_trapezium() only accepts non-negative values""" ) return 1 / 2 * (basea + basea) * height def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> float: if radius < 0: raise ValueError("""area_circle() only accepts non-negative values""" ) return pi * radius**2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if radius_x < 0 or radius_y < 0: raise ValueError("""area_ellipse() only accepts non-negative values""" ) return pi * radius_x * radius_y def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if diagonal_a < 0 or diagonal_a < 0: raise ValueError("""area_rhombus() only accepts non-negative values""" ) return 1 / 2 * diagonal_a * diagonal_a def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if not isinstance(UpperCamelCase , UpperCamelCase ) or sides < 3: raise ValueError( """area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides""" ) elif length < 0: raise ValueError( """area_reg_polygon() only accepts non-negative values as \ length of a side""" ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('''[DEMO] Areas of various geometric shapes: \n''') print(F'Rectangle: {area_rectangle(10, 20) = }') print(F'Square: {area_square(10) = }') print(F'Triangle: {area_triangle(10, 10) = }') print(F'Triangle: {area_triangle_three_sides(5, 12, 13) = }') print(F'Parallelogram: {area_parallelogram(10, 20) = }') print(F'Rhombus: {area_rhombus(10, 20) = }') print(F'Trapezium: {area_trapezium(10, 20, 30) = }') print(F'Circle: {area_circle(20) = }') print(F'Ellipse: {area_ellipse(10, 20) = }') print('''\nSurface Areas of various geometric shapes: \n''') print(F'Cube: {surface_area_cube(20) = }') print(F'Cuboid: {surface_area_cuboid(10, 20, 30) = }') print(F'Sphere: {surface_area_sphere(20) = }') print(F'Hemisphere: {surface_area_hemisphere(20) = }') print(F'Cone: {surface_area_cone(10, 20) = }') print(F'Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }') print(F'Cylinder: {surface_area_cylinder(10, 20) = }') print(F'Torus: {surface_area_torus(20, 10) = }') print(F'Equilateral Triangle: {area_reg_polygon(3, 10) = }') print(F'Square: {area_reg_polygon(4, 10) = }') print(F'Reqular Pentagon: {area_reg_polygon(5, 10) = }')
631
'''simple docstring''' # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : str = [False] * len(UpperCamelCase ) lowerCamelCase__ : str = [-1] * len(UpperCamelCase ) def dfs(UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Union[str, Any] = c for u in graph[v]: if not visited[u]: dfs(UpperCamelCase , 1 - c ) for i in range(len(UpperCamelCase ) ): if not visited[i]: dfs(UpperCamelCase , 0 ) for i in range(len(UpperCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph _A : int ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
631
1
'''simple docstring''' from sklearn.metrics import fa_score import datasets _A : Union[str, Any] =''' The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) ''' _A : List[str] =''' Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`. - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives. - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {\'f1\': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results[\'f1\'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results[\'f1\'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro") >>> print(round(results[\'f1\'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro") >>> print(round(results[\'f1\'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted") >>> print(round(results[\'f1\'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {\'f1\': array([0.8, 0. , 0. ])} ''' _A : List[Any] =''' @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def lowerCamelCase_ ( self: Dict ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""int32""" ) ), """references""": datasets.Sequence(datasets.Value("""int32""" ) ), } if self.config_name == """multilabel""" else { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"""] , ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple , UpperCamelCase__: int=None , UpperCamelCase__: Dict=1 , UpperCamelCase__: Tuple="binary" , UpperCamelCase__: Dict=None ): lowerCamelCase__ : str = fa_score( UpperCamelCase__ , UpperCamelCase__ , labels=UpperCamelCase__ , pos_label=UpperCamelCase__ , average=UpperCamelCase__ , sample_weight=UpperCamelCase__ ) return {"f1": float(UpperCamelCase__ ) if score.size == 1 else score}
631
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Optional[int] = dataset lowerCamelCase__ : Optional[int] = process lowerCamelCase__ : List[str] = params def __len__( self: List[str] ): return len(self.dataset ) def __getitem__( self: Any , UpperCamelCase__: int ): lowerCamelCase__ : Dict = self.dataset[i] lowerCamelCase__ : Union[str, Any] = self.process(UpperCamelCase__ , **self.params ) return processed class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): lowerCamelCase__ : int = loader lowerCamelCase__ : str = infer lowerCamelCase__ : Optional[int] = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : int = loader_batch_size # Internal bookkeeping lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None def __len__( self: Dict ): return len(self.loader ) def __iter__( self: Optional[int] ): lowerCamelCase__ : List[Any] = iter(self.loader ) return self def lowerCamelCase_ ( self: Any ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowerCamelCase__ : str = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowerCamelCase__ : int = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first lowerCamelCase__ : str = element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : Tuple = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : List[str] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : int = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowerCamelCase__ : List[str] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : Optional[Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : int = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowerCamelCase__ : str = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowerCamelCase__ : Optional[int] = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def lowerCamelCase_ ( self: List[Any] ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowerCamelCase__ : Optional[Any] = next(self.iterator ) lowerCamelCase__ : List[str] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Optional[Any] = processed else: lowerCamelCase__ : Union[str, Any] = list(processed.keys() )[0] lowerCamelCase__ : Any = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Any = len(UpperCamelCase__ ) else: lowerCamelCase__ : List[str] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : Union[str, Any] = observed_batch_size # Setting internal index to unwrap the batch lowerCamelCase__ : List[Any] = processed lowerCamelCase__ : List[Any] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class _lowercase ( _lowercase ): def __init__( self: List[str] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any]=None ): super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self: Union[str, Any] ): lowerCamelCase__ : str = iter(self.loader ) lowerCamelCase__ : int = None return self def lowerCamelCase_ ( self: str ): if self.subiterator is None: lowerCamelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowerCamelCase__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowerCamelCase__ : Any = self.infer(next(self.iterator ) , **self.params ) lowerCamelCase__ : Union[str, Any] = next(self.subiterator ) return processed class _lowercase ( _lowercase ): def __iter__( self: List[Any] ): lowerCamelCase__ : int = iter(self.loader ) return self def lowerCamelCase_ ( self: Tuple ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowerCamelCase__ : List[str] = False lowerCamelCase__ : Union[str, Any] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : Any = self.loader_batch_item() lowerCamelCase__ : Tuple = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: lowerCamelCase__ : str = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Dict = processed else: lowerCamelCase__ : Dict = list(processed.keys() )[0] lowerCamelCase__ : Dict = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) else: lowerCamelCase__ : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : str = observed_batch_size lowerCamelCase__ : str = processed lowerCamelCase__ : Optional[int] = 0 while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : List[Any] = self.loader_batch_item() lowerCamelCase__ : str = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: lowerCamelCase__ : Optional[Any] = processed lowerCamelCase__ : Optional[int] = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) return accumulator class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str ): lowerCamelCase__ : Union[str, Any] = dataset lowerCamelCase__ : str = key def __len__( self: Optional[Any] ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Any ): return self.dataset[i][self.key] class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str , UpperCamelCase__: str ): lowerCamelCase__ : str = dataset lowerCamelCase__ : Dict = keya lowerCamelCase__ : List[str] = keya def __len__( self: str ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Union[str, Any] ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
631
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A : List[str] =logging.get_logger(__name__) _A : str ={ '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _lowercase ( _lowercase ): a = """convbert""" def __init__( self: Any , UpperCamelCase__: Dict=30_522 , UpperCamelCase__: List[Any]=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: str=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: Optional[Any]=0.1 , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: Dict=512 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: int=0.02 , UpperCamelCase__: Dict=1e-12 , UpperCamelCase__: List[str]=1 , UpperCamelCase__: List[Any]=0 , UpperCamelCase__: Tuple=2 , UpperCamelCase__: int=768 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: Tuple=9 , UpperCamelCase__: Optional[int]=1 , UpperCamelCase__: str=None , **UpperCamelCase__: int , ): super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) lowerCamelCase__ : Tuple = vocab_size lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : Dict = num_hidden_layers lowerCamelCase__ : Optional[Any] = num_attention_heads lowerCamelCase__ : List[str] = intermediate_size lowerCamelCase__ : Tuple = hidden_act lowerCamelCase__ : Optional[Any] = hidden_dropout_prob lowerCamelCase__ : Union[str, Any] = attention_probs_dropout_prob lowerCamelCase__ : str = max_position_embeddings lowerCamelCase__ : List[str] = type_vocab_size lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : Tuple = layer_norm_eps lowerCamelCase__ : Dict = embedding_size lowerCamelCase__ : Union[str, Any] = head_ratio lowerCamelCase__ : Optional[int] = conv_kernel_size lowerCamelCase__ : Any = num_groups lowerCamelCase__ : int = classifier_dropout class _lowercase ( _lowercase ): @property def lowerCamelCase_ ( self: str ): if self.task == "multiple-choice": lowerCamelCase__ : int = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase__ : str = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
631
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys _A : Dict ='''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
631
1
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
631
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _A : Any ={ '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : str =[ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> str: if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) lowerCamelCase__ : Tuple = str(bin(UpperCamelCase ) )[2:] # remove the leading "0b" lowerCamelCase__ : List[Any] = str(bin(UpperCamelCase ) )[2:] lowerCamelCase__ : str = max(len(UpperCamelCase ) , len(UpperCamelCase ) ) return "0b" + "".join( str(int("""1""" in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(UpperCamelCase ) , b_binary.zfill(UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : List[str] ={ '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """audio-spectrogram-transformer""" def __init__( self: str , UpperCamelCase__: Any=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: List[Any]=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: Optional[Any]="gelu" , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: Union[str, Any]=0.02 , UpperCamelCase__: Dict=1e-12 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=10 , UpperCamelCase__: List[str]=10 , UpperCamelCase__: Any=1_024 , UpperCamelCase__: Optional[Any]=128 , **UpperCamelCase__: Union[str, Any] , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : List[str] = num_attention_heads lowerCamelCase__ : Optional[int] = intermediate_size lowerCamelCase__ : List[Any] = hidden_act lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : str = attention_probs_dropout_prob lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[str] = layer_norm_eps lowerCamelCase__ : List[Any] = patch_size lowerCamelCase__ : List[str] = qkv_bias lowerCamelCase__ : Dict = frequency_stride lowerCamelCase__ : List[Any] = time_stride lowerCamelCase__ : str = max_length lowerCamelCase__ : Dict = num_mel_bins
631
1
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = IFImgaImgSuperResolutionPipeline a = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""} a = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""} ) a = PipelineTesterMixin.required_optional_params - {"""latents"""} def lowerCamelCase_ ( self: Any ): return self._get_superresolution_dummy_components() def lowerCamelCase_ ( self: Any , UpperCamelCase__: Dict , UpperCamelCase__: Any=0 ): if str(UpperCamelCase__ ).startswith("""mps""" ): lowerCamelCase__ : Tuple = torch.manual_seed(UpperCamelCase__ ) else: lowerCamelCase__ : Any = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) lowerCamelCase__ : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = floats_tensor((1, 3, 16, 16) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowerCamelCase_ ( self: Union[str, Any] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowerCamelCase_ ( self: Tuple ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def lowerCamelCase_ ( self: Optional[Any] ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowerCamelCase_ ( self: Optional[int] ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowerCamelCase_ ( self: Optional[int] ): self._test_save_load_local() def lowerCamelCase_ ( self: List[str] ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
631
'''simple docstring''' import argparse import os import re import packaging.version _A : List[str] ='''examples/''' _A : Any ={ '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } _A : int ={ '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } _A : int ='''README.md''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> str: with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : List[str] = f.read() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = REPLACE_PATTERNS[pattern] lowerCamelCase__ : Dict = replace.replace("""VERSION""" , UpperCamelCase ) lowerCamelCase__ : str = re_pattern.sub(UpperCamelCase , UpperCamelCase ) with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: for folder, directories, fnames in os.walk(UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(UpperCamelCase , UpperCamelCase ) , UpperCamelCase , pattern="""examples""" ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> List[Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if not patch: update_version_in_examples(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: lowerCamelCase__ : Dict = """🤗 Transformers currently provides the following architectures""" lowerCamelCase__ : Dict = """1. Want to contribute a new model?""" with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : int = f.readlines() # Find the start of the list. lowerCamelCase__ : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowerCamelCase__ : Optional[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): lowerCamelCase__ : List[Any] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: lowerCamelCase__ : int = f.read() lowerCamelCase__ : Optional[Any] = REPLACE_PATTERNS["""init"""][0].search(UpperCamelCase ).groups()[0] return packaging.version.parse(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase=False ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: lowerCamelCase__ : List[str] = default_version.base_version elif patch: lowerCamelCase__ : Any = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowerCamelCase__ : List[Any] = f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowerCamelCase__ : Any = input(f'''Which version are you releasing? [{default_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Optional[int] = default_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase , patch=UpperCamelCase ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def SCREAMING_SNAKE_CASE_ () -> List[str]: lowerCamelCase__ : Optional[int] = get_version() lowerCamelCase__ : Any = f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowerCamelCase__ : Any = current_version.base_version # Check with the user we got that right. lowerCamelCase__ : List[Any] = input(f'''Which version are we developing now? [{dev_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Dict = dev_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') _A : List[str] =parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
631
1
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _A : List[Any] =logging.get_logger() @dataclass class _lowercase : a = 42 a = field(default_factory=_lowercase ) a = field(default_factory=_lowercase ) def lowerCamelCase_ ( self: Dict , UpperCamelCase__: List[Any] , UpperCamelCase__: Tensor , UpperCamelCase__: Tensor ): lowerCamelCase__ : List[str] = len(list(m.modules() ) ) == 1 or isinstance(UpperCamelCase__ , nn.Convad ) or isinstance(UpperCamelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCamelCase__ ) def __call__( self: Optional[int] , UpperCamelCase__: Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCamelCase__ ) [x.remove() for x in self.handles] return self @property def lowerCamelCase_ ( self: List[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCamelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class _lowercase : a = 42 a = 42 a = 1 a = field(default_factory=_lowercase ) a = field(default_factory=_lowercase ) a = True def __call__( self: Union[str, Any] , UpperCamelCase__: Tensor ): lowerCamelCase__ : Dict = Tracker(self.dest )(UpperCamelCase__ ).parametrized lowerCamelCase__ : str = Tracker(self.src )(UpperCamelCase__ ).parametrized lowerCamelCase__ : Any = list(filter(lambda UpperCamelCase__ : type(UpperCamelCase__ ) not in self.src_skip , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = list(filter(lambda UpperCamelCase__ : type(UpperCamelCase__ ) not in self.dest_skip , UpperCamelCase__ ) ) if len(UpperCamelCase__ ) != len(UpperCamelCase__ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(UpperCamelCase__ )} operations while''' F''' destination module has {len(UpperCamelCase__ )}.''' ) for dest_m, src_m in zip(UpperCamelCase__ , UpperCamelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class _lowercase ( nn.Module ): def __init__( self: Optional[Any] , UpperCamelCase__: nn.Module ): super().__init__() lowerCamelCase__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(("""conv1""", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("""block""" ), F'''Unexpected layer name {k}''' lowerCamelCase__ : Union[str, Any] = len(UpperCamelCase__ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) lowerCamelCase__ : str = nn.ModuleDict(UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Tensor ): return get_trunk_forward_outputs( UpperCamelCase__ , out_feat_keys=UpperCamelCase__ , feature_blocks=self._feature_blocks , ) class _lowercase ( _lowercase ): def lowerCamelCase_ ( self: Any , UpperCamelCase__: str ): lowerCamelCase__ : Optional[int] = x.split("""-""" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self: Tuple , UpperCamelCase__: str ): # default to timm! if x not in self: lowerCamelCase__ : Dict = self.convert_name_to_timm(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = partial(lambda: (timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ).eval(), None) ) else: lowerCamelCase__ : Dict = super().__getitem__(UpperCamelCase__ ) return val class _lowercase ( _lowercase ): def __getitem__( self: int , UpperCamelCase__: str ): if "seer" in x and "in1k" not in x: lowerCamelCase__ : Optional[Any] = RegNetModel else: lowerCamelCase__ : Optional[int] = RegNetForImageClassification return val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> List[Any]: for from_key, to_key in keys: lowerCamelCase__ : Union[str, Any] = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = True , ) -> Dict: print(f'''Converting {name}...''' ) with torch.no_grad(): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = from_model_func() lowerCamelCase__ : Tuple = our_model_func(UpperCamelCase ).eval() lowerCamelCase__ : List[str] = ModuleTransfer(src=UpperCamelCase , dest=UpperCamelCase , raise_if_mismatch=UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = torch.randn((1, 3, 224, 224) ) module_transfer(UpperCamelCase ) if from_state_dict is not None: lowerCamelCase__ : Optional[int] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: lowerCamelCase__ : Optional[int] = [("""0.clf.0.weight""", """classifier.1.weight"""), ("""0.clf.0.bias""", """classifier.1.bias""")] lowerCamelCase__ : int = manually_copy_vissl_head(UpperCamelCase , our_model.state_dict() , UpperCamelCase ) our_model.load_state_dict(UpperCamelCase ) lowerCamelCase__ : int = our_model(UpperCamelCase , output_hidden_states=UpperCamelCase ) lowerCamelCase__ : List[str] = ( our_outputs.logits if isinstance(UpperCamelCase , UpperCamelCase ) else our_outputs.last_hidden_state ) lowerCamelCase__ : List[Any] = from_model(UpperCamelCase ) lowerCamelCase__ : Optional[Any] = from_output[-1] if type(UpperCamelCase ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: lowerCamelCase__ : Union[str, Any] = our_outputs.hidden_states[-1] assert torch.allclose(UpperCamelCase , UpperCamelCase ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message="""Add model""" , use_temp_dir=UpperCamelCase , ) lowerCamelCase__ : str = 224 if """seer""" not in name else 384 # we can use the convnext one lowerCamelCase__ : Any = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" , size=UpperCamelCase ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase , ) print(f'''Pushed {name}''' ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase = None , UpperCamelCase = True ) -> Optional[int]: lowerCamelCase__ : Dict = """imagenet-1k-id2label.json""" lowerCamelCase__ : Dict = 1000 lowerCamelCase__ : Any = (1, num_labels) lowerCamelCase__ : List[Any] = """huggingface/label-files""" lowerCamelCase__ : Optional[Any] = num_labels lowerCamelCase__ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(UpperCamelCase , UpperCamelCase , repo_type="""dataset""" ) ) , """r""" ) ) lowerCamelCase__ : Tuple = {int(UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : Tuple = idalabel lowerCamelCase__ : Tuple = {v: k for k, v in idalabel.items()} lowerCamelCase__ : int = partial(UpperCamelCase , num_labels=UpperCamelCase , idalabel=UpperCamelCase , labelaid=UpperCamelCase ) lowerCamelCase__ : Any = { """regnet-x-002""": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="""x""" ), """regnet-x-004""": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="""x""" ), """regnet-x-006""": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="""x""" ), """regnet-x-008""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="""x""" ), """regnet-x-016""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="""x""" ), """regnet-x-032""": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="""x""" ), """regnet-x-040""": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="""x""" ), """regnet-x-064""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="""x""" ), """regnet-x-080""": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="""x""" ), """regnet-x-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="""x""" ), """regnet-x-160""": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="""x""" ), """regnet-x-320""": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="""x""" ), # y variant """regnet-y-002""": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), """regnet-y-004""": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), """regnet-y-006""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), """regnet-y-008""": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), """regnet-y-016""": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), """regnet-y-032""": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), """regnet-y-040""": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), """regnet-y-064""": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), """regnet-y-080""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), """regnet-y-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), """regnet-y-160""": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), """regnet-y-320""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 """regnet-y-320-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), """regnet-y-640-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), """regnet-y-1280-seer""": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), """regnet-y-2560-seer""": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), """regnet-y-10b-seer""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 11110, 28280] , groups_width=1010 ), # finetuned on imagenet """regnet-y-320-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), """regnet-y-640-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), """regnet-y-1280-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), """regnet-y-2560-seer-in1k""": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 11110, 28280] , groups_width=1010 ), } lowerCamelCase__ : List[Any] = NameToOurModelFuncMap() lowerCamelCase__ : Any = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(UpperCamelCase , UpperCamelCase ) -> Tuple[nn.Module, Dict]: lowerCamelCase__ : Any = torch.hub.load_state_dict_from_url(UpperCamelCase , model_dir=str(UpperCamelCase ) , map_location="""cpu""" ) lowerCamelCase__ : Dict = model_func() # check if we have a head, if yes add it lowerCamelCase__ : int = files["""classy_state_dict"""]["""base_model"""]["""model"""] lowerCamelCase__ : Dict = model_state_dict["""trunk"""] model.load_state_dict(UpperCamelCase ) return model.eval(), model_state_dict["heads"] # pretrained lowerCamelCase__ : Union[str, Any] = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCamelCase__ : List[Any] = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCamelCase__ : Optional[int] = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCamelCase__ : str = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch""" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned lowerCamelCase__ : List[str] = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCamelCase__ : Dict = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCamelCase__ : str = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCamelCase__ : Union[str, Any] = partial( UpperCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch""" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( UpperCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , UpperCamelCase , UpperCamelCase , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( UpperCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) return config, expected_shape if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported regnet* architecture,''' ''' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) _A : Optional[Any] =parser.parse_args() _A : Path =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
631
'''simple docstring''' import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow _A : Union[str, Any] =False class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: Dict , UpperCamelCase__: str=32 ): set_seed(0 ) lowerCamelCase__ : Optional[int] = UNetaDModel(sample_size=UpperCamelCase__ , in_channels=3 , out_channels=3 ) lowerCamelCase__ : List[Any] = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Optional[Any] = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCamelCase__ : List[Any] = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) lowerCamelCase__ : Any = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCamelCase__ : str = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randn((4, 3, 32, 32) ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randint(0 , 1_000 , (4,) ).long().to(UpperCamelCase__ ) for _ in range(4 )] # train with a DDPM scheduler lowerCamelCase__ , lowerCamelCase__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : str = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : str = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Tuple = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : Dict = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Union[str, Any] = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) )
631
1
'''simple docstring''' from math import ceil, sqrt def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 1000000 ) -> int: lowerCamelCase__ : Optional[int] = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__ : Optional[int] = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__ : Any = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F'{solution() = }')
631
'''simple docstring''' from statistics import mean import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : Optional[int] = 0 # Number of processes finished lowerCamelCase__ : Union[str, Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowerCamelCase__ : Tuple = [0] * no_of_process # List to include calculation results lowerCamelCase__ : List[str] = [0] * no_of_process # Sort by arrival time. lowerCamelCase__ : Union[str, Any] = [burst_time[i] for i in np.argsort(UpperCamelCase )] lowerCamelCase__ : List[Any] = [process_name[i] for i in np.argsort(UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: lowerCamelCase__ : str = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowerCamelCase__ : Union[str, Any] = arrival_time[i] lowerCamelCase__ : Any = 0 # Index showing the location of the process being performed lowerCamelCase__ : Union[str, Any] = 0 # Saves the current response ratio. lowerCamelCase__ : Any = 0 for i in range(0 , UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowerCamelCase__ : Optional[int] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowerCamelCase__ : int = temp lowerCamelCase__ : str = i # Calculate the turn around time lowerCamelCase__ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowerCamelCase__ : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : int = [0] * no_of_process for i in range(0 , UpperCamelCase ): lowerCamelCase__ : Optional[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _A : List[str] =5 _A : Optional[Any] =['''A''', '''B''', '''C''', '''D''', '''E'''] _A : Optional[int] =[1, 2, 3, 4, 5] _A : Dict =[1, 2, 3, 4, 5] _A : Any =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _A : Optional[int] =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
631
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A : List[str] =logging.get_logger(__name__) _A : int ={ '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/config.json''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/config.json''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/config.json''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/config.json''', '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json''', '''roberta-large-openai-detector''': '''https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """roberta""" def __init__( self: Optional[Any] , UpperCamelCase__: Union[str, Any]=50_265 , UpperCamelCase__: Any=768 , UpperCamelCase__: Optional[int]=12 , UpperCamelCase__: Any=12 , UpperCamelCase__: Optional[Any]=3_072 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: int=0.1 , UpperCamelCase__: str=0.1 , UpperCamelCase__: Optional[int]=512 , UpperCamelCase__: List[Any]=2 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Optional[Any]=1e-12 , UpperCamelCase__: Union[str, Any]=1 , UpperCamelCase__: str=0 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: Optional[Any]="absolute" , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: Tuple=None , **UpperCamelCase__: Union[str, Any] , ): super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase__ : Tuple = vocab_size lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : Any = num_hidden_layers lowerCamelCase__ : Union[str, Any] = num_attention_heads lowerCamelCase__ : Any = hidden_act lowerCamelCase__ : Optional[int] = intermediate_size lowerCamelCase__ : Optional[int] = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Optional[int] = max_position_embeddings lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : List[str] = layer_norm_eps lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Union[str, Any] = use_cache lowerCamelCase__ : Any = classifier_dropout class _lowercase ( _lowercase ): @property def lowerCamelCase_ ( self: Tuple ): if self.task == "multiple-choice": lowerCamelCase__ : int = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase__ : Union[str, Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
631
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
631
1
'''simple docstring''' import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def SCREAMING_SNAKE_CASE_ (UpperCamelCase=32 , UpperCamelCase=10 , UpperCamelCase=100 , UpperCamelCase=1026 , UpperCamelCase=True , UpperCamelCase="data/tokenized_stories_train_wikitext103.jbl" , UpperCamelCase="igf_context_pairs.jbl" , ) -> Optional[Any]: set_seed(3 ) # generate train_data and objective_set lowerCamelCase__ , lowerCamelCase__ : Dict = generate_datasets( UpperCamelCase , UpperCamelCase , number=UpperCamelCase , min_len=1026 , trim=UpperCamelCase ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? lowerCamelCase__ : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model lowerCamelCase__ : str = load_gpta("""gpt2""" ).to(UpperCamelCase ) print("""computing perplexity on objective set""" ) lowerCamelCase__ : Optional[Any] = compute_perplexity(UpperCamelCase , UpperCamelCase , UpperCamelCase ).item() print("""perplexity on objective set:""" , UpperCamelCase ) # collect igf pairs and save to file demo.jbl collect_objective_set(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=15 , UpperCamelCase=128 , UpperCamelCase=100 , UpperCamelCase="igf_model.pt" , ) -> int: set_seed(42 ) # Load pre-trained model lowerCamelCase__ : int = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model lowerCamelCase__ : Union[str, Any] = SecondaryLearner(UpperCamelCase ) # Train secondary learner lowerCamelCase__ : Tuple = train_secondary_learner( UpperCamelCase , UpperCamelCase , max_epochs=UpperCamelCase , batch_size=UpperCamelCase , eval_freq=100 , igf_model_path=UpperCamelCase , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=32 , UpperCamelCase=1000 , UpperCamelCase=16 , UpperCamelCase=1.0 , UpperCamelCase=recopy_gpta , UpperCamelCase=None , UpperCamelCase=10 , UpperCamelCase="gpt2_finetuned.pt" , ) -> List[str]: lowerCamelCase__ : Optional[Any] = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) lowerCamelCase__ : List[str] = RandomSampler(UpperCamelCase ) lowerCamelCase__ : str = DataLoader(UpperCamelCase , sampler=UpperCamelCase ) lowerCamelCase__ : Optional[Any] = max_steps // (len(UpperCamelCase )) + 1 lowerCamelCase__ : Optional[int] = 0 lowerCamelCase__ : Optional[Any] = torch.zeros((1, context_len) , dtype=torch.long , device=UpperCamelCase ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = recopy_model(UpperCamelCase , UpperCamelCase , UpperCamelCase ) model.train() if secondary_learner is not None: secondary_learner.to(UpperCamelCase ) secondary_learner.eval() lowerCamelCase__ : Union[str, Any] = [] lowerCamelCase__ : Optional[Any] = 0 lowerCamelCase__ : Union[str, Any] = [] lowerCamelCase__ : Any = [] # Compute the performance of the transformer model at the beginning lowerCamelCase__ : Tuple = compute_perplexity(UpperCamelCase , UpperCamelCase , UpperCamelCase ) test_perps.append(UpperCamelCase ) print("""Test perplexity, step""" , UpperCamelCase , """:""" , UpperCamelCase ) for epoch in range(int(UpperCamelCase ) ): for step, example in enumerate(UpperCamelCase ): torch.cuda.empty_cache() lowerCamelCase__ : Any = random.randint(0 , example.size(2 ) - context_len - 1 ) lowerCamelCase__ : Any = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() lowerCamelCase__ : List[str] = model(UpperCamelCase , labels=UpperCamelCase ) lowerCamelCase__ : Dict = True if secondary_learner is not None: lowerCamelCase__ : Dict = secondary_learner.forward( torch.tensor(UpperCamelCase , dtype=torch.long , device=UpperCamelCase ).unsqueeze(0 ) )[0].item() observed_qs.append(float(UpperCamelCase ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: lowerCamelCase__ : Any = -1 if predicted_q < threshold: lowerCamelCase__ : List[Any] = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) lowerCamelCase__ : str = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() lowerCamelCase__ : Optional[int] = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: lowerCamelCase__ : Tuple = compute_perplexity(UpperCamelCase , UpperCamelCase , UpperCamelCase ) test_perps.append(UpperCamelCase ) print("""Test perplexity, step""" , UpperCamelCase , """:""" , UpperCamelCase ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , UpperCamelCase ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def SCREAMING_SNAKE_CASE_ () -> Tuple: lowerCamelCase__ : List[Any] = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=UpperCamelCase , default=UpperCamelCase , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=UpperCamelCase , default=UpperCamelCase , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=UpperCamelCase , type=UpperCamelCase , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=UpperCamelCase , default=UpperCamelCase , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=UpperCamelCase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=UpperCamelCase , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=UpperCamelCase , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1000 , type=UpperCamelCase , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=UpperCamelCase , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=UpperCamelCase , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=UpperCamelCase , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=UpperCamelCase , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1026 , type=UpperCamelCase , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=UpperCamelCase , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=UpperCamelCase , type=UpperCamelCase , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=UpperCamelCase , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=UpperCamelCase , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=UpperCamelCase , type=UpperCamelCase , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=UpperCamelCase , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner lowerCamelCase__ : Optional[Any] = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner lowerCamelCase__ : Optional[int] = training_secondary_learner( UpperCamelCase , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model lowerCamelCase__ : int = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1026 , trim=UpperCamelCase ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( UpperCamelCase , UpperCamelCase , UpperCamelCase , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=UpperCamelCase , secondary_learner=UpperCamelCase , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
631
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowercase : def __init__( self: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Optional[int]=30 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: List[str]=3 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=True , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Any=5 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Dict=37 , UpperCamelCase__: List[Any]="gelu" , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: List[Any]=10 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Optional[int]=3 , UpperCamelCase__: Dict=0.6 , UpperCamelCase__: int=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Optional[Any] = patch_size lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Any = is_training lowerCamelCase__ : Union[str, Any] = use_labels lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Any = hidden_dropout_prob lowerCamelCase__ : Optional[int] = attention_probs_dropout_prob lowerCamelCase__ : List[Any] = type_sequence_label_size lowerCamelCase__ : int = initializer_range lowerCamelCase__ : List[str] = mask_ratio lowerCamelCase__ : List[Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowerCamelCase__ : str = (image_size // patch_size) ** 2 lowerCamelCase__ : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: str ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int ): lowerCamelCase__ : Tuple = ViTMAEModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : List[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): lowerCamelCase__ : int = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Any = (self.image_size // self.patch_size) ** 2 lowerCamelCase__ : str = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowerCamelCase__ : Dict = 1 lowerCamelCase__ : Optional[int] = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = config_and_inputs lowerCamelCase__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () a = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} a = False a = False a = False a = False def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Tuple = ViTMAEModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase_ ( self: Dict ): pass def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Any = model_class(UpperCamelCase__ ) lowerCamelCase__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Any = [*signature.parameters.keys()] lowerCamelCase__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] ): # make masks reproducible np.random.seed(2 ) lowerCamelCase__ : Tuple = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) lowerCamelCase__ : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCamelCase__ : Tuple = torch.from_numpy(UpperCamelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowerCamelCase__ : Tuple = pt_noise super().check_pt_tf_models(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Optional[int] = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs[0].cpu().numpy() lowerCamelCase__ : List[str] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model_class.from_pretrained(UpperCamelCase__ ) model.to(UpperCamelCase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) # Make sure we don't have nans lowerCamelCase__ : Dict = after_outputs[0].cpu().numpy() lowerCamelCase__ : Tuple = 0 lowerCamelCase__ : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase__ , 1e-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: Any ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase_ ( self: Tuple ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Optional[int] ): pass @slow def lowerCamelCase_ ( self: List[str] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Tuple = ViTMAEModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> List[Any]: lowerCamelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: List[str] ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self: Tuple ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) lowerCamelCase__ : str = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : int = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowerCamelCase__ : List[str] = ViTMAEConfig() lowerCamelCase__ : int = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowerCamelCase__ : Any = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ , noise=torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ ) ) # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : str = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCamelCase__ ) , atol=1e-4 ) )
631
1
'''simple docstring''' import math def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[int]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(UpperCamelCase ) 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 : Tuple ='''Enter the base and the power separated by a comma: ''' _A , _A : int =map(int, input(prompt).split(''',''')) _A , _A : str =map(int, input(prompt).split(''',''')) # We find the log of each number, using the function res(), which takes two # arguments. _A : str =res(xa, ya) _A : Tuple =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''')
631
'''simple docstring''' import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _lowercase ( _lowercase ): a = """""" a = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a = None # compression type in fsspec. ex: "gzip" a = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self: str , UpperCamelCase__: str = "" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , **UpperCamelCase__: List[Any] ): super().__init__(self , **UpperCamelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode lowerCamelCase__ : List[Any] = fsspec.open( UpperCamelCase__ , mode="""rb""" , protocol=UpperCamelCase__ , compression=self.compression , client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) lowerCamelCase__ : str = os.path.basename(self.file.path.split("""::""" )[0] ) lowerCamelCase__ : Union[str, Any] = ( self.compressed_name[: self.compressed_name.rindex(""".""" )] if """.""" in self.compressed_name else self.compressed_name ) lowerCamelCase__ : Tuple = None @classmethod def lowerCamelCase_ ( cls: Optional[int] , UpperCamelCase__: Optional[int] ): # compressed file paths are always relative to the archive root return super()._strip_protocol(UpperCamelCase__ ).lstrip("""/""" ) def lowerCamelCase_ ( self: Tuple ): if self.dir_cache is None: lowerCamelCase__ : Dict = {**self.file.fs.info(self.file.path ), """name""": self.uncompressed_name} lowerCamelCase__ : int = {f["""name"""]: f} def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: str ): return self.file.open().read() def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[int]=None , UpperCamelCase__: Tuple=True , UpperCamelCase__: Tuple=None , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Union[str, Any] = self._strip_protocol(UpperCamelCase__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class _lowercase ( _lowercase ): a = """bz2""" a = """bz2""" a = """.bz2""" class _lowercase ( _lowercase ): a = """gzip""" a = """gzip""" a = """.gz""" class _lowercase ( _lowercase ): a = """lz4""" a = """lz4""" a = """.lz4""" class _lowercase ( _lowercase ): a = """xz""" a = """xz""" a = """.xz""" class _lowercase ( _lowercase ): a = """zstd""" a = """zstd""" a = """.zst""" def __init__( self: int , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , UpperCamelCase__: int = DEFAULT_BLOCK_SIZE , **UpperCamelCase__: Dict , ): super().__init__( fo=UpperCamelCase__ , mode=UpperCamelCase__ , target_protocol=UpperCamelCase__ , target_options=UpperCamelCase__ , block_size=UpperCamelCase__ , **UpperCamelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 lowerCamelCase__ : Tuple = self.file.__enter__ class _lowercase : def __init__( self: Optional[int] , UpperCamelCase__: Any ): lowerCamelCase__ : Optional[int] = file_ def __enter__( self: List[Any] ): self._file.__enter__() return self def __exit__( self: Any , *UpperCamelCase__: str , **UpperCamelCase__: Any ): self._file.__exit__(*UpperCamelCase__ , **UpperCamelCase__ ) def __iter__( self: Any ): return iter(self._file ) def lowerCamelCase_ ( self: List[Any] ): return next(self._file ) def __getattr__( self: List[str] , UpperCamelCase__: Dict ): return getattr(self._file , UpperCamelCase__ ) def fixed_enter(*UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[str] ): return WrappedFile(_enter(*UpperCamelCase__ , **UpperCamelCase__ ) ) lowerCamelCase__ : Optional[Any] = fixed_enter
631
1
'''simple docstring''' class _lowercase : def __init__( self: Any , UpperCamelCase__: list ): lowerCamelCase__ : Any = set_counts lowerCamelCase__ : int = max(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = len(UpperCamelCase__ ) lowerCamelCase__ : int = [1] * num_sets lowerCamelCase__ : Any = list(range(UpperCamelCase__ ) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: int , UpperCamelCase__: int ): lowerCamelCase__ : List[Any] = self.get_parent(UpperCamelCase__ ) lowerCamelCase__ : List[str] = self.get_parent(UpperCamelCase__ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] lowerCamelCase__ : List[Any] = 0 lowerCamelCase__ : Dict = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 lowerCamelCase__ : Dict = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] lowerCamelCase__ : Union[str, Any] = 0 lowerCamelCase__ : Any = src_parent lowerCamelCase__ : List[str] = self.set_counts[src_parent] lowerCamelCase__ : Union[str, Any] = max(self.max_set , UpperCamelCase__ ) return True def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: int ): if self.parents[disj_set] == disj_set: return disj_set lowerCamelCase__ : str = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
631
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() _A : int =logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: print("""Loading config file...""" ) def flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase="" , UpperCamelCase="." ): lowerCamelCase__ : Optional[int] = [] for k, v in d.items(): lowerCamelCase__ : Optional[int] = parent_key + sep + k if parent_key else k if isinstance(UpperCamelCase , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase , sep=UpperCamelCase ).items() ) else: items.append((new_key, v) ) return dict(UpperCamelCase ) lowerCamelCase__ : Any = argparse.Namespace() with open(UpperCamelCase , """r""" ) as yaml_file: try: lowerCamelCase__ : int = yaml.load(UpperCamelCase , Loader=yaml.FullLoader ) lowerCamelCase__ : Tuple = flatten_yaml_as_dict(UpperCamelCase ) for k, v in flat_cfg.items(): setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) except yaml.YAMLError as exc: logger.error("""Error while loading config file: {}. Error message: {}""".format(UpperCamelCase , str(UpperCamelCase ) ) ) return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Union[str, Any] = MobileViTVaConfig() lowerCamelCase__ : str = False # dataset if task_name.startswith("""imagenet1k_""" ): lowerCamelCase__ : Optional[Any] = 1000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : int = 384 else: lowerCamelCase__ : Optional[int] = 256 lowerCamelCase__ : str = """imagenet-1k-id2label.json""" elif task_name.startswith("""imagenet21k_to_1k_""" ): lowerCamelCase__ : Tuple = 21000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : str = 384 else: lowerCamelCase__ : Any = 256 lowerCamelCase__ : int = """imagenet-22k-id2label.json""" elif task_name.startswith("""ade20k_""" ): lowerCamelCase__ : Dict = 151 lowerCamelCase__ : str = 512 lowerCamelCase__ : List[Any] = """ade20k-id2label.json""" lowerCamelCase__ : Union[str, Any] = True elif task_name.startswith("""voc_""" ): lowerCamelCase__ : Tuple = 21 lowerCamelCase__ : Optional[int] = 512 lowerCamelCase__ : List[Any] = """pascal-voc-id2label.json""" lowerCamelCase__ : Tuple = True # orig_config lowerCamelCase__ : Optional[int] = load_orig_config_file(UpperCamelCase ) assert getattr(UpperCamelCase , """model.classification.name""" , -1 ) == "mobilevit_v2", "Invalid model" lowerCamelCase__ : int = getattr(UpperCamelCase , """model.classification.mitv2.width_multiplier""" , 1.0 ) assert ( getattr(UpperCamelCase , """model.classification.mitv2.attn_norm_layer""" , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.classification.activation.name""" , """swish""" ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: lowerCamelCase__ : Any = getattr(UpperCamelCase , """model.segmentation.output_stride""" , 16 ) if "_deeplabv3" in task_name: lowerCamelCase__ : str = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_rates""" , [12, 24, 36] ) lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_out_channels""" , 512 ) lowerCamelCase__ : List[Any] = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_dropout""" , 0.1 ) # id2label lowerCamelCase__ : Tuple = """huggingface/label-files""" lowerCamelCase__ : Optional[Any] = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase__ : Union[str, Any] = {int(UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : int = idalabel lowerCamelCase__ : Optional[Any] = {v: k for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any: lowerCamelCase__ : List[Any] = dct.pop(UpperCamelCase ) lowerCamelCase__ : Dict = val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> Tuple: if base_model: lowerCamelCase__ : Optional[int] = """""" else: lowerCamelCase__ : Optional[Any] = """mobilevitv2.""" lowerCamelCase__ : List[str] = [] for k in state_dict.keys(): if k[:8] == "encoder.": lowerCamelCase__ : Optional[Any] = k[8:] else: lowerCamelCase__ : Optional[Any] = k if ".block." in k: lowerCamelCase__ : Dict = k_new.replace(""".block.""" , """.""" ) if ".conv." in k: lowerCamelCase__ : List[Any] = k_new.replace(""".conv.""" , """.convolution.""" ) if ".norm." in k: lowerCamelCase__ : str = k_new.replace(""".norm.""" , """.normalization.""" ) if "conv_1." in k: lowerCamelCase__ : Any = k_new.replace("""conv_1.""" , f'''{model_prefix}conv_stem.''' ) for i in [1, 2]: if f'''layer_{i}.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.''' , f'''{model_prefix}encoder.layer.{i-1}.layer.''' ) if ".exp_1x1." in k: lowerCamelCase__ : Dict = k_new.replace(""".exp_1x1.""" , """.expand_1x1.""" ) if ".red_1x1." in k: lowerCamelCase__ : str = k_new.replace(""".red_1x1.""" , """.reduce_1x1.""" ) for i in [3, 4, 5]: if f'''layer_{i}.0.''' in k: lowerCamelCase__ : List[str] = k_new.replace(f'''layer_{i}.0.''' , f'''{model_prefix}encoder.layer.{i-1}.downsampling_layer.''' ) if f'''layer_{i}.1.local_rep.0.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.1.local_rep.0.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_kxk.''' ) if f'''layer_{i}.1.local_rep.1.''' in k: lowerCamelCase__ : Dict = k_new.replace(f'''layer_{i}.1.local_rep.1.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_1x1.''' ) for i in [3, 4, 5]: if i == 3: lowerCamelCase__ : int = [0, 1] elif i == 4: lowerCamelCase__ : str = [0, 1, 2, 3] elif i == 5: lowerCamelCase__ : Dict = [0, 1, 2] for j in j_in: if f'''layer_{i}.1.global_rep.{j}.''' in k: lowerCamelCase__ : List[Any] = k_new.replace( f'''layer_{i}.1.global_rep.{j}.''' , f'''{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.''' ) if f'''layer_{i}.1.global_rep.{j+1}.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace( f'''layer_{i}.1.global_rep.{j+1}.''' , f'''{model_prefix}encoder.layer.{i-1}.layernorm.''' ) if f'''layer_{i}.1.conv_proj.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace(f'''layer_{i}.1.conv_proj.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_projection.''' ) if "pre_norm_attn.0." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.0.""" , """layernorm_before.""" ) if "pre_norm_attn.1." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.1.""" , """attention.""" ) if "pre_norm_ffn.0." in k: lowerCamelCase__ : Optional[Any] = k_new.replace("""pre_norm_ffn.0.""" , """layernorm_after.""" ) if "pre_norm_ffn.1." in k: lowerCamelCase__ : Union[str, Any] = k_new.replace("""pre_norm_ffn.1.""" , """ffn.conv1.""" ) if "pre_norm_ffn.3." in k: lowerCamelCase__ : List[Any] = k_new.replace("""pre_norm_ffn.3.""" , """ffn.conv2.""" ) if "classifier.1." in k: lowerCamelCase__ : Tuple = k_new.replace("""classifier.1.""" , """classifier.""" ) if "seg_head." in k: lowerCamelCase__ : Optional[int] = k_new.replace("""seg_head.""" , """segmentation_head.""" ) if ".aspp_layer." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_pool.""" , """.""" ) rename_keys.append((k, k_new) ) return rename_keys def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: lowerCamelCase__ : Union[str, Any] = [] for k in state_dict.keys(): if k.startswith("""seg_head.aux_head.""" ): keys_to_ignore.append(UpperCamelCase ) for k in keys_to_ignore: state_dict.pop(UpperCamelCase , UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Dict: lowerCamelCase__ : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" lowerCamelCase__ : Tuple = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCamelCase__ : str = get_mobilevitva_config(UpperCamelCase , UpperCamelCase ) # load original state_dict lowerCamelCase__ : List[str] = torch.load(UpperCamelCase , map_location="""cpu""" ) # load huggingface model if task_name.startswith("""ade20k_""" ) or task_name.startswith("""voc_""" ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation(UpperCamelCase ).eval() lowerCamelCase__ : Tuple = False else: lowerCamelCase__ : int = MobileViTVaForImageClassification(UpperCamelCase ).eval() lowerCamelCase__ : Optional[Any] = False # remove and rename some keys of load the original model lowerCamelCase__ : Tuple = checkpoint remove_unused_keys(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = create_rename_keys(UpperCamelCase , base_model=UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # load modified state_dict model.load_state_dict(UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor lowerCamelCase__ : int = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) lowerCamelCase__ : Dict = image_processor(images=prepare_img() , return_tensors="""pt""" ) lowerCamelCase__ : str = model(**UpperCamelCase ) # verify classification model if task_name.startswith("""imagenet""" ): lowerCamelCase__ : Dict = outputs.logits lowerCamelCase__ : Optional[Any] = logits.argmax(-1 ).item() print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] ) if task_name.startswith("""imagenet1k_256""" ) and config.width_multiplier == 1.0: # expected_logits for base variant lowerCamelCase__ : Optional[Any] = torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01] ) assert torch.allclose(logits[0, :3] , UpperCamelCase , atol=1E-4 ) Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(f'''Saving model {task_name} 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 __name__ == "__main__": _A : Optional[int] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''imagenet1k_256''', type=str, help=( '''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ''' ''' Classification (ImageNet-1k) - MobileViTV2 (256x256) : imagenet1k_256 - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384 - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) : imagenet21k_to_1k_256 - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on ImageNet-1k 384x384) : imagenet21k_to_1k_384 Segmentation - ADE20K Dataset : ade20k_deeplabv3 - Pascal VOC 2012 Dataset: voc_deeplabv3 ''' ), choices=[ '''imagenet1k_256''', '''imagenet1k_384''', '''imagenet21k_to_1k_256''', '''imagenet21k_to_1k_384''', '''ade20k_deeplabv3''', '''voc_deeplabv3''', ], ) parser.add_argument( '''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) _A : Dict =parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
631
1
'''simple docstring''' import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _lowercase ( unittest.TestCase ): a = MODEL_FOR_MASKED_LM_MAPPING a = TF_MODEL_FOR_MASKED_LM_MAPPING def lowerCamelCase_ ( self: Tuple ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""" ) lowerCamelCase__ : Tuple = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"""sequence""": """My name is grouped""", """score""": 2.1e-05, """token""": 38_015, """token_str""": """ grouped"""}, {"""sequence""": """My name is accuser""", """score""": 2.1e-05, """token""": 25_506, """token_str""": """ accuser"""}, ] , ) lowerCamelCase__ : int = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ { """sequence""": """The largest city in France is grouped""", """score""": 2.1e-05, """token""": 38_015, """token_str""": """ grouped""", }, { """sequence""": """The largest city in France is accuser""", """score""": 2.1e-05, """token""": 25_506, """token_str""": """ accuser""", }, ] , ) lowerCamelCase__ : Union[str, Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"""sequence""": """My name is Clara""", """score""": 2e-05, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Patrick""", """score""": 2e-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 1.9e-05, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Optional[int] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""" ) lowerCamelCase__ : int = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"""sequence""": """My name is Maul""", """score""": 2.2e-05, """token""": 35_676, """token_str""": """ Maul"""}, {"""sequence""": """My name isELS""", """score""": 2.2e-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) lowerCamelCase__ : int = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ { """sequence""": """The largest city in France is Maul""", """score""": 2.2e-05, """token""": 35_676, """token_str""": """ Maul""", }, {"""sequence""": """The largest city in France isELS""", """score""": 2.2e-05, """token""": 16_416, """token_str""": """ELS"""}, ] , ) lowerCamelCase__ : Any = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ {"""sequence""": """My name is Patrick""", """score""": 2.1e-05, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Te""", """score""": 2e-05, """token""": 2_941, """token_str""": """ Te"""}, {"""sequence""": """My name is Clara""", """score""": 2e-05, """token""": 13_606, """token_str""": """ Clara"""}, ] , ) lowerCamelCase__ : List[Any] = unmasker("""My name is <mask> <mask>""" , top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ , decimals=6 ) , [ [ { """score""": 2.2e-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is Maul<mask></s>""", }, {"""score""": 2.2e-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""}, ], [ { """score""": 2.2e-05, """token""": 35_676, """token_str""": """ Maul""", """sequence""": """<s>My name is<mask> Maul</s>""", }, {"""score""": 2.2e-05, """token""": 16_416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""}, ], ] , ) @require_torch_gpu def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Optional[int] = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""" ) # convert model to fp16 pipe.model.half() lowerCamelCase__ : int = pipe("""Paris is the [MASK] of France.""" ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) @slow @require_torch def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Optional[int] = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""" ) self.run_large_test(UpperCamelCase__ ) @slow @require_tf def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : str = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""" ) self.run_large_test(UpperCamelCase__ ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: List[Any] ): lowerCamelCase__ : Optional[Any] = unmasker("""My name is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ {"""sequence""": """My name is John""", """score""": 0.008, """token""": 610, """token_str""": """ John"""}, {"""sequence""": """My name is Chris""", """score""": 0.007, """token""": 1_573, """token_str""": """ Chris"""}, ] , ) lowerCamelCase__ : List[str] = unmasker("""The largest city in France is <mask>""" ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ { """sequence""": """The largest city in France is Paris""", """score""": 0.251, """token""": 2_201, """token_str""": """ Paris""", }, { """sequence""": """The largest city in France is Lyon""", """score""": 0.214, """token""": 12_790, """token_str""": """ Lyon""", }, ] , ) lowerCamelCase__ : List[str] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ {"""sequence""": """My name is Patrick""", """score""": 0.005, """token""": 3_499, """token_str""": """ Patrick"""}, {"""sequence""": """My name is Clara""", """score""": 0.000, """token""": 13_606, """token_str""": """ Clara"""}, {"""sequence""": """My name is Te""", """score""": 0.000, """token""": 2_941, """token_str""": """ Te"""}, ] , ) @require_torch def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""" ) lowerCamelCase__ : List[str] = None lowerCamelCase__ : Optional[int] = None self.run_pipeline_test(UpperCamelCase__ , [] ) @require_tf def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Optional[int] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""" ) lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : Optional[Any] = None self.run_pipeline_test(UpperCamelCase__ , [] ) def lowerCamelCase_ ( self: int , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Tuple ): if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""" ) lowerCamelCase__ : List[Any] = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = [ F'''This is another {tokenizer.mask_token} test''', ] return fill_masker, examples def lowerCamelCase_ ( self: int , UpperCamelCase__: str , UpperCamelCase__: List[str] ): lowerCamelCase__ : str = fill_masker.tokenizer lowerCamelCase__ : Tuple = fill_masker.model lowerCamelCase__ : Union[str, Any] = fill_masker( F'''This is a {tokenizer.mask_token}''' , ) self.assertEqual( UpperCamelCase__ , [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase__ : List[Any] = fill_masker([F'''This is a {tokenizer.mask_token}'''] ) self.assertEqual( UpperCamelCase__ , [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase__ : Optional[int] = fill_masker([F'''This is a {tokenizer.mask_token}''', F'''Another {tokenizer.mask_token} great test.'''] ) self.assertEqual( UpperCamelCase__ , [ [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ], [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ], ] , ) with self.assertRaises(UpperCamelCase__ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(UpperCamelCase__ ): fill_masker("""This is""" ) self.run_test_top_k(UpperCamelCase__ , UpperCamelCase__ ) self.run_test_targets(UpperCamelCase__ , UpperCamelCase__ ) self.run_test_top_k_targets(UpperCamelCase__ , UpperCamelCase__ ) self.fill_mask_with_duplicate_targets_and_top_k(UpperCamelCase__ , UpperCamelCase__ ) self.fill_mask_with_multiple_masks(UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: str ): lowerCamelCase__ : Tuple = tokenizer.get_vocab() lowerCamelCase__ : Any = sorted(vocab.keys() )[:2] # Pipeline argument lowerCamelCase__ : int = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ , targets=UpperCamelCase__ ) lowerCamelCase__ : str = fill_masker(F'''This is a {tokenizer.mask_token}''' ) self.assertEqual( UpperCamelCase__ , [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase__ : List[str] = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , UpperCamelCase__ ) lowerCamelCase__ : Any = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(UpperCamelCase__ ) ) # Call argument lowerCamelCase__ : Optional[int] = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase__ : Dict = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase__ : Tuple = {vocab[el] for el in targets} self.assertEqual({el["""token"""] for el in outputs} , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["""token_str"""] for el in outputs} , set(UpperCamelCase__ ) ) # Score equivalence lowerCamelCase__ : Optional[Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase__ ) lowerCamelCase__ : List[str] = [top_mask["""token_str"""] for top_mask in outputs] lowerCamelCase__ : List[str] = [top_mask["""score"""] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCamelCase__ ) == set(UpperCamelCase__ ): lowerCamelCase__ : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=UpperCamelCase__ ) lowerCamelCase__ : List[Any] = [top_mask["""score"""] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(UpperCamelCase__ ) , nested_simplify(UpperCamelCase__ ) ) # Raises with invalid with self.assertRaises(UpperCamelCase__ ): lowerCamelCase__ : Any = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(UpperCamelCase__ ): lowerCamelCase__ : Optional[Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[""""""] ) with self.assertRaises(UpperCamelCase__ ): lowerCamelCase__ : Optional[int] = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets="""""" ) def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] ): lowerCamelCase__ : int = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ , top_k=2 ) lowerCamelCase__ : str = fill_masker(F'''This is a {tokenizer.mask_token}''' ) self.assertEqual( UpperCamelCase__ , [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ] , ) lowerCamelCase__ : Any = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase__ : Tuple = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 ) self.assertEqual( UpperCamelCase__ , [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ] , ) self.assertEqual(nested_simplify(UpperCamelCase__ ) , nested_simplify(UpperCamelCase__ ) ) def lowerCamelCase_ ( self: int , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : Dict = tokenizer.get_vocab() lowerCamelCase__ : List[Any] = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) # top_k=2, ntargets=3 lowerCamelCase__ : int = sorted(vocab.keys() )[:3] lowerCamelCase__ : List[Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 , targets=UpperCamelCase__ ) # If we use the most probably targets, and filter differently, we should still # have the same results lowerCamelCase__ : List[Any] = [el["""token_str"""] for el in sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : x["score"] , reverse=UpperCamelCase__ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(UpperCamelCase__ ).issubset(UpperCamelCase__ ): lowerCamelCase__ : Tuple = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=3 , targets=UpperCamelCase__ ) # They should yield exactly the same result self.assertEqual(nested_simplify(UpperCamelCase__ ) , nested_simplify(UpperCamelCase__ ) ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: List[str] ): lowerCamelCase__ : Dict = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = tokenizer.get_vocab() # String duplicates + id duplicates lowerCamelCase__ : int = sorted(vocab.keys() )[:3] lowerCamelCase__ : List[Any] = [targets[0], targets[1], targets[0], targets[2], targets[1]] lowerCamelCase__ : str = fill_masker(F'''My name is {tokenizer.mask_token}''' , targets=UpperCamelCase__ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(UpperCamelCase__ ) , 3 ) def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: str , UpperCamelCase__: Dict ): lowerCamelCase__ : str = FillMaskPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) lowerCamelCase__ : int = fill_masker( F'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''' , top_k=2 ) self.assertEqual( UpperCamelCase__ , [ [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ], [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ], [ {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, {"""sequence""": ANY(UpperCamelCase__ ), """score""": ANY(UpperCamelCase__ ), """token""": ANY(UpperCamelCase__ ), """token_str""": ANY(UpperCamelCase__ )}, ], ] , )
631
'''simple docstring''' import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _lowercase ( _lowercase ): def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCamelCase__ , """width_multiplier""" ) ) class _lowercase : def __init__( self: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: str=13 , UpperCamelCase__: Any=64 , UpperCamelCase__: Optional[Any]=2 , UpperCamelCase__: str=3 , UpperCamelCase__: List[str]="swish" , UpperCamelCase__: Any=3 , UpperCamelCase__: Optional[int]=32 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: int=0.02 , UpperCamelCase__: Dict=True , UpperCamelCase__: Dict=True , UpperCamelCase__: Any=10 , UpperCamelCase__: int=None , UpperCamelCase__: List[Any]=0.25 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Optional[int]=0.0 , ): lowerCamelCase__ : Any = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : str = patch_size lowerCamelCase__ : Optional[int] = num_channels lowerCamelCase__ : Optional[Any] = make_divisible(512 * width_multiplier , divisor=8 ) lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : Any = conv_kernel_size lowerCamelCase__ : Any = output_stride lowerCamelCase__ : Union[str, Any] = classifier_dropout_prob lowerCamelCase__ : List[str] = use_labels lowerCamelCase__ : Optional[Any] = is_training lowerCamelCase__ : List[str] = num_labels lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[Any] = scope lowerCamelCase__ : Tuple = width_multiplier lowerCamelCase__ : List[Any] = ffn_dropout lowerCamelCase__ : Any = attn_dropout def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Tuple = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase__ : str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCamelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCamelCase_ ( self: List[Any] ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Union[str, Any] = MobileViTVaModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : str = model(UpperCamelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : Tuple = self.num_labels lowerCamelCase__ : Dict = MobileViTVaForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str ): lowerCamelCase__ : List[str] = self.num_labels lowerCamelCase__ : Union[str, Any] = MobileViTVaForSemanticSegmentation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase__ : List[Any] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Any = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) a = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) a = False a = False a = False a = False def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = MobileViTVaModelTester(self ) lowerCamelCase__ : List[str] = MobileViTVaConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def lowerCamelCase_ ( self: Union[str, Any] ): pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Tuple ): pass def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ , lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Tuple = [*signature.parameters.keys()] lowerCamelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): def check_hidden_states_output(UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs.hidden_states lowerCamelCase__ : List[Any] = 5 self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase__ : int = 2 for i in range(len(UpperCamelCase__ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCamelCase__ , lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : int = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__ : str = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Union[str, Any] = MobileViTVaModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> Optional[int]: lowerCamelCase__ : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: Tuple ): return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[Any] = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = self.default_image_processor lowerCamelCase__ : List[Any] = prepare_img() lowerCamelCase__ : Any = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : int = model(**UpperCamelCase__ ) # verify the logits lowerCamelCase__ : str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Any = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Union[str, Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Optional[Any] = model(**UpperCamelCase__ ) lowerCamelCase__ : str = outputs.logits # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Any = torch.tensor( [ [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]], [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]], [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]], ] , device=UpperCamelCase__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Optional[Any] = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : List[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Dict = model(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = outputs.logits.detach().cpu() lowerCamelCase__ : List[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ , target_sizes=[(50, 60)] ) lowerCamelCase__ : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ ) lowerCamelCase__ : int = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ )
631
1
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable _A : List[str] ={'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DPTConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : int =['''DPTFeatureExtractor'''] _A : Tuple =['''DPTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''DPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DPTForDepthEstimation''', '''DPTForSemanticSegmentation''', '''DPTModel''', '''DPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys _A : List[str] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _A : Optional[Any] =logging.get_logger(__name__) _A : Dict ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _A : Tuple ={ '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } _A : List[Any] ={ '''gpt-neox-20b''': 2_048, } class _lowercase ( _lowercase ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["""input_ids""", """attention_mask"""] def __init__( self: Optional[int] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: int=None , UpperCamelCase__: Tuple=None , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Union[str, Any]="<|endoftext|>" , UpperCamelCase__: Tuple=False , **UpperCamelCase__: str , ): super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , **UpperCamelCase__ , ) lowerCamelCase__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: lowerCamelCase__ : Any = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) ) lowerCamelCase__ : Dict = add_prefix_space lowerCamelCase__ : Optional[int] = pre_tok_class(**UpperCamelCase__ ) lowerCamelCase__ : Dict = add_prefix_space def lowerCamelCase_ ( self: int , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): lowerCamelCase__ : Optional[Any] = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: "Conversation" ): lowerCamelCase__ : str = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [self.eos_token_id] ) if len(UpperCamelCase__ ) > self.model_max_length: lowerCamelCase__ : int = input_ids[-self.model_max_length :] return input_ids
631
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor _A : int =logging.get_logger(__name__) class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , *UpperCamelCase__: str , **UpperCamelCase__: Optional[Any] ): warnings.warn( """The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use SegformerImageProcessor instead.""" , UpperCamelCase__ , ) super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
631
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A : Dict ={ '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A : Dict ={ '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin _A : int =get_tests_dir('''fixtures/test_sentencepiece.model''') _A : Tuple ={'''target_lang''': '''fi''', '''source_lang''': '''en'''} _A : int ='''>>zh<<''' _A : Dict ='''Helsinki-NLP/''' if is_torch_available(): _A : List[Any] ='''pt''' elif is_tf_available(): _A : Optional[int] ='''tf''' else: _A : Dict ='''jax''' @require_sentencepiece class _lowercase ( _lowercase , unittest.TestCase ): a = MarianTokenizer a = False a = True def lowerCamelCase_ ( self: List[str] ): super().setUp() lowerCamelCase__ : List[Any] = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] lowerCamelCase__ : Optional[Any] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) lowerCamelCase__ : Optional[int] = Path(self.tmpdirname ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) lowerCamelCase__ : Dict = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self: Optional[Any] , **UpperCamelCase__: Any ): return MarianTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] ): return ( "This is a test", "This is a test", ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Any = """</s>""" lowerCamelCase__ : List[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__ ) , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(UpperCamelCase__ ) , 9 ) def lowerCamelCase_ ( self: int ): self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def lowerCamelCase_ ( self: int ): lowerCamelCase__ : List[Any] = MarianTokenizer.from_pretrained(F'''{ORG_NAME}opus-mt-en-de''' ) lowerCamelCase__ : Optional[int] = en_de_tokenizer(["""I am a small frog"""] , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [38, 121, 14, 697, 38_848, 0] self.assertListEqual(UpperCamelCase__ , batch.input_ids[0] ) lowerCamelCase__ : List[str] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : Tuple = [x.name for x in Path(UpperCamelCase__ ).glob("""*""" )] self.assertIn("""source.spm""" , UpperCamelCase__ ) MarianTokenizer.from_pretrained(UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : List[Any] = self.get_tokenizer() lowerCamelCase__ : Any = tok( ["""I am a small frog""" * 1_000, """I am a small frog"""] , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Dict = tok(["""I am a tiny frog""", """I am a small frog"""] , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def lowerCamelCase_ ( self: List[str] ): # fmt: off lowerCamelCase__ : int = {"""input_ids""": [[43_495, 462, 20, 42_164, 1_369, 52, 464, 132, 1_703, 492, 13, 7_491, 38_999, 6, 8, 464, 132, 1_703, 492, 13, 4_669, 37_867, 13, 7_525, 27, 1_593, 988, 13, 33_972, 7_029, 6, 20, 8_251, 383, 2, 270, 5_866, 3_788, 2, 2_353, 8_251, 12_338, 2, 13_958, 387, 2, 3_629, 6_953, 188, 2_900, 2, 13_958, 8_011, 11_501, 23, 8_460, 4_073, 34_009, 20, 435, 11_439, 27, 8, 8_460, 4_073, 6_004, 20, 9_988, 375, 27, 33, 266, 1_945, 1_076, 1_350, 37_867, 3_288, 5, 577, 1_076, 4_374, 8, 5_082, 5, 26_453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10_767, 6, 316, 304, 4_239, 3, 0], [148, 15_722, 19, 1_839, 12, 1_350, 13, 22_327, 5_082, 5_418, 47_567, 35_938, 59, 318, 19_552, 108, 2_183, 54, 14_976, 4_835, 32, 547, 1_114, 8, 315, 2_417, 5, 92, 19_088, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100], [36, 6_395, 12_570, 39_147, 11_597, 6, 266, 4, 45_405, 7_296, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase__ , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Union[str, Any] = MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) lowerCamelCase__ : str = """Tämä on testi""" lowerCamelCase__ : Any = """This is a test""" lowerCamelCase__ : int = [76, 7, 2_047, 2] lowerCamelCase__ : List[str] = [69, 12, 11, 940, 2] lowerCamelCase__ : Tuple = tokenizer(UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = tokenizer(text_target=UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Tuple = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
631
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass _A : List[Any] =(3, 9, -11, 0, 7, 5, 1, -1) _A : int =(4, 6, 2, 0, 8, 10, 3, -2) @dataclass class _lowercase : a = 42 a = 42 class _lowercase : def __init__( self: int , UpperCamelCase__: Iterable[int] ): lowerCamelCase__ : Node | None = None for i in sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ): lowerCamelCase__ : Dict = Node(UpperCamelCase__ , self.head ) def __iter__( self: Optional[int] ): lowerCamelCase__ : Dict = self.head while node: yield node.data lowerCamelCase__ : List[str] = node.next_node def __len__( self: Optional[Any] ): return sum(1 for _ in self ) def __str__( self: Dict ): return " -> ".join([str(UpperCamelCase__ ) for node in self] ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> SortedLinkedList: return SortedLinkedList(list(UpperCamelCase ) + list(UpperCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() _A : Any =SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Optional[Any] =logging.get_logger(__name__) _A : Optional[int] ={ '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """rwkv""" a = {"""max_position_embeddings""": """context_length"""} def __init__( self: Tuple , UpperCamelCase__: Optional[Any]=50_277 , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Tuple=4_096 , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Dict=None , UpperCamelCase__: Dict=None , UpperCamelCase__: int=1e-5 , UpperCamelCase__: Any=0 , UpperCamelCase__: str=0 , UpperCamelCase__: Union[str, Any]=6 , UpperCamelCase__: Optional[int]=False , UpperCamelCase__: Dict=True , **UpperCamelCase__: Dict , ): lowerCamelCase__ : Dict = vocab_size lowerCamelCase__ : Optional[Any] = context_length lowerCamelCase__ : Optional[Any] = hidden_size lowerCamelCase__ : Any = num_hidden_layers lowerCamelCase__ : int = attention_hidden_size if attention_hidden_size is not None else hidden_size lowerCamelCase__ : Union[str, Any] = intermediate_size if intermediate_size is not None else 4 * hidden_size lowerCamelCase__ : List[str] = layer_norm_epsilon lowerCamelCase__ : int = rescale_every lowerCamelCase__ : Optional[int] = use_cache lowerCamelCase__ : Dict = bos_token_id lowerCamelCase__ : Any = eos_token_id super().__init__( tie_word_embeddings=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> list: lowerCamelCase__ : str = int(UpperCamelCase ) if n_element < 1: lowerCamelCase__ : int = ValueError("""a should be a positive number""" ) raise my_error lowerCamelCase__ : Tuple = [1] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[str] = (0, 0, 0) lowerCamelCase__ : List[str] = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _A : str =input('''Enter the last number (nth term) of the Hamming Number Series: ''') print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''') _A : List[Any] =hamming(int(n)) print('''-----------------------------------------------------''') print(F'The list with nth numbers is: {hamming_numbers}') print('''-----------------------------------------------------''')
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str =logging.get_logger(__name__) _A : int ={ '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """roc_bert""" def __init__( self: Optional[Any] , UpperCamelCase__: Any=30_522 , UpperCamelCase__: Optional[Any]=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: Tuple=12 , UpperCamelCase__: Tuple=3_072 , UpperCamelCase__: str="gelu" , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Dict=512 , UpperCamelCase__: str=2 , UpperCamelCase__: str=0.02 , UpperCamelCase__: Tuple=1e-12 , UpperCamelCase__: Any=True , UpperCamelCase__: Union[str, Any]=0 , UpperCamelCase__: List[Any]="absolute" , UpperCamelCase__: Any=None , UpperCamelCase__: Any=True , UpperCamelCase__: Optional[int]=True , UpperCamelCase__: Union[str, Any]=768 , UpperCamelCase__: int=910 , UpperCamelCase__: Tuple=512 , UpperCamelCase__: int=24_858 , UpperCamelCase__: Optional[Any]=True , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : Tuple = num_attention_heads lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : List[Any] = use_cache lowerCamelCase__ : Tuple = enable_pronunciation lowerCamelCase__ : Union[str, Any] = enable_shape lowerCamelCase__ : Union[str, Any] = pronunciation_embed_dim lowerCamelCase__ : Any = pronunciation_vocab_size lowerCamelCase__ : int = shape_embed_dim lowerCamelCase__ : Tuple = shape_vocab_size lowerCamelCase__ : Optional[Any] = concat_input lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Dict = classifier_dropout super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : List[str] =logging.get_logger(__name__) _A : str ={ '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/config.json''', '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json''', '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/config.json''', '''funnel-transformer/medium-base''': '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json''', '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/config.json''', '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json''', '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json''', '''funnel-transformer/xlarge-base''': '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """funnel""" a = { """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", } def __init__( self: Optional[int] , UpperCamelCase__: Any=30_522 , UpperCamelCase__: Optional[int]=[4, 4, 4] , UpperCamelCase__: str=None , UpperCamelCase__: List[Any]=2 , UpperCamelCase__: Tuple=768 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Union[str, Any]=64 , UpperCamelCase__: int=3_072 , UpperCamelCase__: List[Any]="gelu_new" , UpperCamelCase__: Tuple=0.1 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: Any=0.1 , UpperCamelCase__: int=None , UpperCamelCase__: Optional[Any]=1e-9 , UpperCamelCase__: Dict="mean" , UpperCamelCase__: Any="relative_shift" , UpperCamelCase__: str=True , UpperCamelCase__: Dict=True , UpperCamelCase__: int=True , **UpperCamelCase__: Any , ): lowerCamelCase__ : List[str] = vocab_size lowerCamelCase__ : List[str] = block_sizes lowerCamelCase__ : List[Any] = [1] * len(UpperCamelCase__ ) if block_repeats is None else block_repeats assert len(UpperCamelCase__ ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." lowerCamelCase__ : Tuple = num_decoder_layers lowerCamelCase__ : int = d_model lowerCamelCase__ : Optional[Any] = n_head lowerCamelCase__ : int = d_head lowerCamelCase__ : Optional[int] = d_inner lowerCamelCase__ : List[Any] = hidden_act lowerCamelCase__ : Union[str, Any] = hidden_dropout lowerCamelCase__ : str = attention_dropout lowerCamelCase__ : Union[str, Any] = activation_dropout lowerCamelCase__ : int = initializer_range lowerCamelCase__ : Dict = initializer_std lowerCamelCase__ : Union[str, Any] = layer_norm_eps assert pooling_type in [ "mean", "max", ], F'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' lowerCamelCase__ : Union[str, Any] = pooling_type assert attention_type in [ "relative_shift", "factorized", ], F'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' lowerCamelCase__ : Dict = attention_type lowerCamelCase__ : Optional[int] = separate_cls lowerCamelCase__ : Dict = truncate_seq lowerCamelCase__ : Union[str, Any] = pool_q_only super().__init__(**UpperCamelCase__ ) @property def lowerCamelCase_ ( self: Optional[int] ): return sum(self.block_sizes ) @num_hidden_layers.setter def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Dict ): raise NotImplementedError( """This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.""" ) @property def lowerCamelCase_ ( self: Optional[int] ): return len(self.block_sizes ) @num_blocks.setter def lowerCamelCase_ ( self: Dict , UpperCamelCase__: Optional[Any] ): raise NotImplementedError("""This model does not support the setting of `num_blocks`. Please set `block_sizes`.""" )
631
'''simple docstring''' import sys import turtle def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> None: my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( '''Correct format for using this script: ''' '''python fractals.py <int:depth_for_fractal>''' ) _A : Any =turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('''red''') _A : Dict =[(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
631
1
'''simple docstring''' _A : Optional[int] ='''Input must be a string of 8 numbers plus letter''' _A : Tuple ='''TRWAGMYFPDXBNJZSQVHLCKE''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> bool: if not isinstance(UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : str = f'''Expected string as input, found {type(UpperCamelCase ).__name__}''' raise TypeError(UpperCamelCase ) lowerCamelCase__ : Dict = spanish_id.replace("""-""" , """""" ).upper() if len(UpperCamelCase ) != 9: raise ValueError(UpperCamelCase ) try: lowerCamelCase__ : List[Any] = int(spanish_id_clean[0:8] ) lowerCamelCase__ : List[Any] = spanish_id_clean[8] except ValueError as ex: raise ValueError(UpperCamelCase ) from ex if letter.isdigit(): raise ValueError(UpperCamelCase ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
631
'''simple docstring''' from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class _lowercase : def __init__( self: int , UpperCamelCase__: Dict , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Union[str, Any]=7 , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: List[Any]=True , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: int=True , UpperCamelCase__: List[Any]=99 , UpperCamelCase__: Tuple=32 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Optional[int]=37 , UpperCamelCase__: Any="gelu" , UpperCamelCase__: Any=0.1 , UpperCamelCase__: int=0.1 , UpperCamelCase__: Optional[Any]=512 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Tuple=3 , UpperCamelCase__: Optional[int]=4 , UpperCamelCase__: Union[str, Any]=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Union[str, Any] = 13 lowerCamelCase__ : Any = 7 lowerCamelCase__ : int = True lowerCamelCase__ : Optional[Any] = True lowerCamelCase__ : Dict = True lowerCamelCase__ : List[str] = True lowerCamelCase__ : str = 99 lowerCamelCase__ : Dict = 384 lowerCamelCase__ : Optional[Any] = 2 lowerCamelCase__ : Optional[int] = 4 lowerCamelCase__ : Optional[Any] = 37 lowerCamelCase__ : Union[str, Any] = """gelu""" lowerCamelCase__ : int = 0.1 lowerCamelCase__ : Optional[Any] = 0.1 lowerCamelCase__ : List[Any] = 512 lowerCamelCase__ : Optional[Any] = 16 lowerCamelCase__ : Any = 2 lowerCamelCase__ : Optional[Any] = 0.02 lowerCamelCase__ : int = 3 lowerCamelCase__ : List[str] = 4 lowerCamelCase__ : Any = 128 lowerCamelCase__ : List[Any] = 2 lowerCamelCase__ : Optional[Any] = 9 lowerCamelCase__ : Any = 1 lowerCamelCase__ : Optional[int] = None def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : str = None if self.use_input_mask: lowerCamelCase__ : int = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : List[str] = None if self.use_token_type_ids: lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : int = None lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Any = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : List[Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCamelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: Any ): lowerCamelCase__ : List[Any] = TFConvBertModel(config=UpperCamelCase__ ) lowerCamelCase__ : str = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase__ : List[str] = [input_ids, input_mask] lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: Tuple , UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : int = TFConvBertForMaskedLM(config=UpperCamelCase__ ) lowerCamelCase__ : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : int = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : int = self.num_labels lowerCamelCase__ : Dict = TFConvBertForSequenceClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: Dict ): lowerCamelCase__ : Optional[int] = self.num_choices lowerCamelCase__ : Dict = TFConvBertForMultipleChoice(config=UpperCamelCase__ ) lowerCamelCase__ : int = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : List[str] = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Any = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Tuple = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Any , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: int ): lowerCamelCase__ : List[Any] = self.num_labels lowerCamelCase__ : List[str] = TFConvBertForTokenClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Optional[int] = TFConvBertForQuestionAnswering(config=UpperCamelCase__ ) lowerCamelCase__ : int = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : str = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : str = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a = ( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a = False a = False a = False def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Dict = TFConvBertModelTester(self ) lowerCamelCase__ : Dict = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: List[str] ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Dict = True lowerCamelCase__ : Tuple = True if hasattr(UpperCamelCase__ , """use_cache""" ): lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : List[str] = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Tuple = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) for model_class in self.all_model_classes: lowerCamelCase__ : int = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : Dict = len(model(UpperCamelCase__ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ , saved_model=UpperCamelCase__ ) lowerCamelCase__ : int = os.path.join(UpperCamelCase__ , """saved_model""" , """1""" ) lowerCamelCase__ : List[Any] = tf.keras.models.load_model(UpperCamelCase__ ) lowerCamelCase__ : Any = model(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : Dict = outputs["""encoder_hidden_states"""] lowerCamelCase__ : Any = outputs["""encoder_attentions"""] else: lowerCamelCase__ : int = outputs["""hidden_states"""] lowerCamelCase__ : Optional[int] = outputs["""attentions"""] self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Union[str, Any] = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) self.assertIsNotNone(UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : int = getattr(self.model_tester , """decoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Any = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Optional[int] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) def check_decoder_attentions_output(UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) self.assertEqual(out_len % 2 , 0 ) lowerCamelCase__ : Any = outputs.decoder_attentions self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(UpperCamelCase__: List[str] ): lowerCamelCase__ : Any = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: lowerCamelCase__ : int = True lowerCamelCase__ : Any = False lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = len(UpperCamelCase__ ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) lowerCamelCase__ : Tuple = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_decoder_attentions_output(UpperCamelCase__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Dict = model_class(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) # Check attention is always last and order is fine lowerCamelCase__ : List[Any] = True lowerCamelCase__ : int = True lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCamelCase__ ) ) self.assertEqual(model.config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) @require_tf class _lowercase ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) lowerCamelCase__ : Optional[Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ )[0] lowerCamelCase__ : Dict = [1, 6, 768] self.assertEqual(output.shape , UpperCamelCase__ ) lowerCamelCase__ : Dict = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCamelCase__ , atol=1e-4 )
631
1
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> List[Any]: lowerCamelCase__ : List[Any] = 0 if start < end: lowerCamelCase__ : Optional[int] = randint(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Optional[int] = a[end] lowerCamelCase__ : Any = a[pivot] lowerCamelCase__ : str = temp lowerCamelCase__ , lowerCamelCase__ : Tuple = _in_place_partition(UpperCamelCase , UpperCamelCase , UpperCamelCase ) count += _in_place_quick_sort(UpperCamelCase , UpperCamelCase , p - 1 ) count += _in_place_quick_sort(UpperCamelCase , p + 1 , UpperCamelCase ) return count def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Tuple: lowerCamelCase__ : Any = 0 lowerCamelCase__ : Union[str, Any] = randint(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Tuple = a[end] lowerCamelCase__ : Optional[Any] = a[pivot] lowerCamelCase__ : int = temp lowerCamelCase__ : Optional[int] = start - 1 for index in range(UpperCamelCase , UpperCamelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCamelCase__ : Any = new_pivot_index + 1 lowerCamelCase__ : List[Any] = a[new_pivot_index] lowerCamelCase__ : List[str] = a[index] lowerCamelCase__ : Optional[Any] = temp lowerCamelCase__ : Tuple = a[new_pivot_index + 1] lowerCamelCase__ : List[str] = a[end] lowerCamelCase__ : List[Any] = temp return new_pivot_index + 1, count _A : Dict =TemporaryFile() _A : str =100 # 1000 elements are to be sorted _A , _A : Dict =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 : List[str] =np.load(outfile) _A : Optional[int] =len(M) - 1 _A : int =_in_place_quick_sort(M, 0, r) print( '''No of Comparisons for 100 elements selected from a standard normal distribution''' '''is :''' ) print(z)
631
'''simple docstring''' _A : List[str] ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> list: if len(UpperCamelCase ) < 2: return collection def circle_sort_util(UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> bool: lowerCamelCase__ : Optional[int] = False if low == high: return swapped lowerCamelCase__ : Union[str, Any] = low lowerCamelCase__ : Optional[int] = high while left < right: if collection[left] > collection[right]: lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = ( collection[right], collection[left], ) lowerCamelCase__ : List[str] = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: lowerCamelCase__ , lowerCamelCase__ : List[str] = ( collection[right + 1], collection[left], ) lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : Tuple = low + int((high - low) / 2 ) lowerCamelCase__ : Tuple = circle_sort_util(UpperCamelCase , UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : List[Any] = circle_sort_util(UpperCamelCase , mid + 1 , UpperCamelCase ) return swapped or left_swap or right_swap lowerCamelCase__ : Optional[int] = True while is_not_sorted is True: lowerCamelCase__ : str = circle_sort_util(UpperCamelCase , 0 , len(UpperCamelCase ) - 1 ) return collection if __name__ == "__main__": _A : Union[str, Any] =input('''Enter numbers separated by a comma:\n''').strip() _A : Union[str, Any] =[int(item) for item in user_input.split(''',''')] print(circle_sort(unsorted))
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Any =logging.get_logger(__name__) _A : Dict ={ '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class _lowercase ( _lowercase ): a = """trocr""" a = ["""past_key_values"""] a = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Optional[Any] , UpperCamelCase__: int=50_265 , UpperCamelCase__: int=1_024 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Dict=16 , UpperCamelCase__: int=4_096 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: int=512 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Any=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: str=True , UpperCamelCase__: Tuple=False , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Tuple=True , UpperCamelCase__: Dict=1 , UpperCamelCase__: List[str]=0 , UpperCamelCase__: Union[str, Any]=2 , **UpperCamelCase__: str , ): lowerCamelCase__ : Any = vocab_size lowerCamelCase__ : Tuple = d_model lowerCamelCase__ : Any = decoder_layers lowerCamelCase__ : Dict = decoder_attention_heads lowerCamelCase__ : str = decoder_ffn_dim lowerCamelCase__ : Tuple = activation_function lowerCamelCase__ : Dict = max_position_embeddings lowerCamelCase__ : int = dropout lowerCamelCase__ : int = attention_dropout lowerCamelCase__ : List[Any] = activation_dropout lowerCamelCase__ : Union[str, Any] = init_std lowerCamelCase__ : Optional[int] = decoder_layerdrop lowerCamelCase__ : Dict = use_cache lowerCamelCase__ : Any = scale_embedding lowerCamelCase__ : Optional[int] = use_learned_position_embeddings lowerCamelCase__ : List[str] = layernorm_embedding super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
631
1
'''simple docstring''' from typing import TYPE_CHECKING from ..utils import _LazyModule _A : Tuple ={ '''config''': [ '''EXTERNAL_DATA_FORMAT_SIZE_LIMIT''', '''OnnxConfig''', '''OnnxConfigWithPast''', '''OnnxSeq2SeqConfigWithPast''', '''PatchingSpec''', ], '''convert''': ['''export''', '''validate_model_outputs'''], '''features''': ['''FeaturesManager'''], '''utils''': ['''ParameterFormat''', '''compute_serialized_parameters_size'''], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
'''simple docstring''' # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : str = [False] * len(UpperCamelCase ) lowerCamelCase__ : str = [-1] * len(UpperCamelCase ) def dfs(UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Union[str, Any] = c for u in graph[v]: if not visited[u]: dfs(UpperCamelCase , 1 - c ) for i in range(len(UpperCamelCase ) ): if not visited[i]: dfs(UpperCamelCase , 0 ) for i in range(len(UpperCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph _A : int ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
631
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A : List[str] ={ '''configuration_mask2former''': [ '''MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Mask2FormerConfig''', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Any =['''Mask2FormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Any =[ '''MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Mask2FormerForUniversalSegmentation''', '''Mask2FormerModel''', '''Mask2FormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _A : int =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
631
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Optional[int] = dataset lowerCamelCase__ : Optional[int] = process lowerCamelCase__ : List[str] = params def __len__( self: List[str] ): return len(self.dataset ) def __getitem__( self: Any , UpperCamelCase__: int ): lowerCamelCase__ : Dict = self.dataset[i] lowerCamelCase__ : Union[str, Any] = self.process(UpperCamelCase__ , **self.params ) return processed class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): lowerCamelCase__ : int = loader lowerCamelCase__ : str = infer lowerCamelCase__ : Optional[int] = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : int = loader_batch_size # Internal bookkeeping lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None def __len__( self: Dict ): return len(self.loader ) def __iter__( self: Optional[int] ): lowerCamelCase__ : List[Any] = iter(self.loader ) return self def lowerCamelCase_ ( self: Any ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowerCamelCase__ : str = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowerCamelCase__ : int = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first lowerCamelCase__ : str = element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : Tuple = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : List[str] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : int = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowerCamelCase__ : List[str] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : Optional[Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : int = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowerCamelCase__ : str = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowerCamelCase__ : Optional[int] = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def lowerCamelCase_ ( self: List[Any] ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowerCamelCase__ : Optional[Any] = next(self.iterator ) lowerCamelCase__ : List[str] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Optional[Any] = processed else: lowerCamelCase__ : Union[str, Any] = list(processed.keys() )[0] lowerCamelCase__ : Any = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Any = len(UpperCamelCase__ ) else: lowerCamelCase__ : List[str] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : Union[str, Any] = observed_batch_size # Setting internal index to unwrap the batch lowerCamelCase__ : List[Any] = processed lowerCamelCase__ : List[Any] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class _lowercase ( _lowercase ): def __init__( self: List[str] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any]=None ): super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self: Union[str, Any] ): lowerCamelCase__ : str = iter(self.loader ) lowerCamelCase__ : int = None return self def lowerCamelCase_ ( self: str ): if self.subiterator is None: lowerCamelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowerCamelCase__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowerCamelCase__ : Any = self.infer(next(self.iterator ) , **self.params ) lowerCamelCase__ : Union[str, Any] = next(self.subiterator ) return processed class _lowercase ( _lowercase ): def __iter__( self: List[Any] ): lowerCamelCase__ : int = iter(self.loader ) return self def lowerCamelCase_ ( self: Tuple ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowerCamelCase__ : List[str] = False lowerCamelCase__ : Union[str, Any] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : Any = self.loader_batch_item() lowerCamelCase__ : Tuple = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: lowerCamelCase__ : str = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Dict = processed else: lowerCamelCase__ : Dict = list(processed.keys() )[0] lowerCamelCase__ : Dict = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) else: lowerCamelCase__ : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : str = observed_batch_size lowerCamelCase__ : str = processed lowerCamelCase__ : Optional[int] = 0 while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : List[Any] = self.loader_batch_item() lowerCamelCase__ : str = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: lowerCamelCase__ : Optional[Any] = processed lowerCamelCase__ : Optional[int] = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) return accumulator class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str ): lowerCamelCase__ : Union[str, Any] = dataset lowerCamelCase__ : str = key def __len__( self: Optional[Any] ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Any ): return self.dataset[i][self.key] class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str , UpperCamelCase__: str ): lowerCamelCase__ : str = dataset lowerCamelCase__ : Dict = keya lowerCamelCase__ : List[str] = keya def __len__( self: str ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Union[str, Any] ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
631
1
'''simple docstring''' import requests _A : Dict ='''''' # <-- Put your OpenWeatherMap appid here! _A : str ='''https://api.openweathermap.org/data/2.5/''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = "Chicago" , UpperCamelCase = APPID ) -> dict: return requests.get(URL_BASE + """weather""" , params=locals() ).json() def SCREAMING_SNAKE_CASE_ (UpperCamelCase = "Kolkata, India" , UpperCamelCase = APPID ) -> dict: return requests.get(URL_BASE + """forecast""" , params=locals() ).json() def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 55.68 , UpperCamelCase = 12.57 , UpperCamelCase = APPID ) -> dict: return requests.get(URL_BASE + """onecall""" , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: _A : Any =input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
631
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys _A : Dict ='''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
631
1
'''simple docstring''' import os def SCREAMING_SNAKE_CASE_ () -> Tuple: with open(os.path.dirname(UpperCamelCase ) + """/p022_names.txt""" ) as file: lowerCamelCase__ : Optional[Any] = str(file.readlines()[0] ) lowerCamelCase__ : Dict = names.replace("""\"""" , """""" ).split(""",""" ) names.sort() lowerCamelCase__ : Any = 0 lowerCamelCase__ : Optional[Any] = 0 for i, name in enumerate(UpperCamelCase ): for letter in name: name_score += ord(UpperCamelCase ) - 64 total_score += (i + 1) * name_score lowerCamelCase__ : Dict = 0 return total_score if __name__ == "__main__": print(solution())
631
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _A : Any ={ '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : str =[ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
1
'''simple docstring''' import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem _A : List[str] =importlib.util.find_spec('''s3fs''') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 _A : List[compression.BaseCompressedFileFileSystem] =[ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: if "://" in dataset_path: lowerCamelCase__ : Dict = dataset_path.split("""://""" )[1] return dataset_path def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> bool: if fs is not None and fs.protocol != "file": return True else: return False def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Any = not is_remote_filesystem(UpperCamelCase ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(UpperCamelCase ) , fs._strip_protocol(UpperCamelCase ) ) else: fs.mv(UpperCamelCase , UpperCamelCase , recursive=UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> None: if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: lowerCamelCase__ : List[Any] = None lowerCamelCase__ : Any = None lowerCamelCase__ : int = threading.Lock()
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : List[str] ={ '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """audio-spectrogram-transformer""" def __init__( self: str , UpperCamelCase__: Any=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: List[Any]=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: Optional[Any]="gelu" , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: Union[str, Any]=0.02 , UpperCamelCase__: Dict=1e-12 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=10 , UpperCamelCase__: List[str]=10 , UpperCamelCase__: Any=1_024 , UpperCamelCase__: Optional[Any]=128 , **UpperCamelCase__: Union[str, Any] , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : List[str] = num_attention_heads lowerCamelCase__ : Optional[int] = intermediate_size lowerCamelCase__ : List[Any] = hidden_act lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : str = attention_probs_dropout_prob lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[str] = layer_norm_eps lowerCamelCase__ : List[Any] = patch_size lowerCamelCase__ : List[str] = qkv_bias lowerCamelCase__ : Dict = frequency_stride lowerCamelCase__ : List[Any] = time_stride lowerCamelCase__ : str = max_length lowerCamelCase__ : Dict = num_mel_bins
631
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor _A : Any =logging.get_logger(__name__) class _lowercase ( _lowercase ): def __init__( self: Dict , *UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[str] ): warnings.warn( """The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DonutImageProcessor instead.""" , UpperCamelCase__ , ) super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
631
'''simple docstring''' import argparse import os import re import packaging.version _A : List[str] ='''examples/''' _A : Any ={ '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } _A : int ={ '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } _A : int ='''README.md''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> str: with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : List[str] = f.read() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = REPLACE_PATTERNS[pattern] lowerCamelCase__ : Dict = replace.replace("""VERSION""" , UpperCamelCase ) lowerCamelCase__ : str = re_pattern.sub(UpperCamelCase , UpperCamelCase ) with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: for folder, directories, fnames in os.walk(UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(UpperCamelCase , UpperCamelCase ) , UpperCamelCase , pattern="""examples""" ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> List[Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if not patch: update_version_in_examples(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: lowerCamelCase__ : Dict = """🤗 Transformers currently provides the following architectures""" lowerCamelCase__ : Dict = """1. Want to contribute a new model?""" with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : int = f.readlines() # Find the start of the list. lowerCamelCase__ : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowerCamelCase__ : Optional[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): lowerCamelCase__ : List[Any] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: lowerCamelCase__ : int = f.read() lowerCamelCase__ : Optional[Any] = REPLACE_PATTERNS["""init"""][0].search(UpperCamelCase ).groups()[0] return packaging.version.parse(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase=False ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: lowerCamelCase__ : List[str] = default_version.base_version elif patch: lowerCamelCase__ : Any = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowerCamelCase__ : List[Any] = f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowerCamelCase__ : Any = input(f'''Which version are you releasing? [{default_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Optional[int] = default_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase , patch=UpperCamelCase ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def SCREAMING_SNAKE_CASE_ () -> List[str]: lowerCamelCase__ : Optional[int] = get_version() lowerCamelCase__ : Any = f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowerCamelCase__ : Any = current_version.base_version # Check with the user we got that right. lowerCamelCase__ : List[Any] = input(f'''Which version are we developing now? [{dev_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Dict = dev_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') _A : List[str] =parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
631
1
'''simple docstring''' import qiskit def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> qiskit.result.counts.Counts: lowerCamelCase__ : Union[str, Any] = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register lowerCamelCase__ : Union[str, Any] = qiskit.QuantumCircuit(UpperCamelCase , UpperCamelCase ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator lowerCamelCase__ : List[Any] = qiskit.execute(UpperCamelCase , UpperCamelCase , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(UpperCamelCase ) if __name__ == "__main__": _A : List[str] =single_qubit_measure(2, 2) print(F'Total count for various states are: {counts}')
631
'''simple docstring''' import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow _A : Union[str, Any] =False class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: Dict , UpperCamelCase__: str=32 ): set_seed(0 ) lowerCamelCase__ : Optional[int] = UNetaDModel(sample_size=UpperCamelCase__ , in_channels=3 , out_channels=3 ) lowerCamelCase__ : List[Any] = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Optional[Any] = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCamelCase__ : List[Any] = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) lowerCamelCase__ : Any = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCamelCase__ : str = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randn((4, 3, 32, 32) ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randint(0 , 1_000 , (4,) ).long().to(UpperCamelCase__ ) for _ in range(4 )] # train with a DDPM scheduler lowerCamelCase__ , lowerCamelCase__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : str = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : str = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Tuple = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : Dict = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Union[str, Any] = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) )
631
1
'''simple docstring''' import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> List[Any]: lowerCamelCase__ : Optional[int] = old_name if "patch_embed" in old_name: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[str] = old_name.split(""".""" ) if layer == "0": lowerCamelCase__ : int = old_name.replace("""0""" , """convolution1""" ) elif layer == "1": lowerCamelCase__ : str = old_name.replace("""1""" , """batchnorm_before""" ) elif layer == "3": lowerCamelCase__ : Any = old_name.replace("""3""" , """convolution2""" ) else: lowerCamelCase__ : Optional[Any] = old_name.replace("""4""" , """batchnorm_after""" ) if "network" in old_name and re.search(r"""\d\.\d""" , UpperCamelCase ): lowerCamelCase__ : str = r"""\b\d{2}\b""" if bool(re.search(UpperCamelCase , UpperCamelCase ) ): lowerCamelCase__ : Optional[Any] = re.search(r"""\d\.\d\d.""" , UpperCamelCase ).group() else: lowerCamelCase__ : Optional[int] = re.search(r"""\d\.\d.""" , UpperCamelCase ).group() if int(match[0] ) < 6: lowerCamelCase__ : List[Any] = old_name.replace(UpperCamelCase , """""" ) lowerCamelCase__ : List[str] = trimmed_name.replace("""network""" , match[0] + """.meta4D_layers.blocks.""" + match[2:-1] ) lowerCamelCase__ : Optional[Any] = """intermediate_stages.""" + trimmed_name else: lowerCamelCase__ : Optional[Any] = old_name.replace(UpperCamelCase , """""" ) if int(match[2] ) < num_meta4D_last_stage: lowerCamelCase__ : List[str] = trimmed_name.replace("""network""" , """meta4D_layers.blocks.""" + match[2] ) else: lowerCamelCase__ : str = str(int(match[2] ) - num_meta4D_last_stage ) lowerCamelCase__ : List[Any] = trimmed_name.replace("""network""" , """meta3D_layers.blocks.""" + layer_index ) if "norm1" in old_name: lowerCamelCase__ : Any = trimmed_name.replace("""norm1""" , """layernorm1""" ) elif "norm2" in old_name: lowerCamelCase__ : Union[str, Any] = trimmed_name.replace("""norm2""" , """layernorm2""" ) elif "fc1" in old_name: lowerCamelCase__ : str = trimmed_name.replace("""fc1""" , """linear_in""" ) elif "fc2" in old_name: lowerCamelCase__ : str = trimmed_name.replace("""fc2""" , """linear_out""" ) lowerCamelCase__ : List[str] = """last_stage.""" + trimmed_name elif "network" in old_name and re.search(r""".\d.""" , UpperCamelCase ): lowerCamelCase__ : Dict = old_name.replace("""network""" , """intermediate_stages""" ) if "fc" in new_name: lowerCamelCase__ : Union[str, Any] = new_name.replace("""fc""" , """convolution""" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): lowerCamelCase__ : Dict = new_name.replace("""norm1""" , """batchnorm_before""" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): lowerCamelCase__ : List[str] = new_name.replace("""norm2""" , """batchnorm_after""" ) if "proj" in new_name: lowerCamelCase__ : Tuple = new_name.replace("""proj""" , """projection""" ) if "dist_head" in new_name: lowerCamelCase__ : Tuple = new_name.replace("""dist_head""" , """distillation_classifier""" ) elif "head" in new_name: lowerCamelCase__ : Any = new_name.replace("""head""" , """classifier""" ) elif "patch_embed" in new_name: lowerCamelCase__ : int = """efficientformer.""" + new_name elif new_name == "norm.weight" or new_name == "norm.bias": lowerCamelCase__ : Dict = new_name.replace("""norm""" , """layernorm""" ) lowerCamelCase__ : Dict = """efficientformer.""" + new_name else: lowerCamelCase__ : str = """efficientformer.encoder.""" + new_name return new_name def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[int]: for key in checkpoint.copy().keys(): lowerCamelCase__ : List[Any] = checkpoint.pop(UpperCamelCase ) lowerCamelCase__ : Optional[Any] = val return checkpoint def SCREAMING_SNAKE_CASE_ () -> str: lowerCamelCase__ : Dict = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowerCamelCase__ : Optional[int] = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) return image def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> List[Any]: lowerCamelCase__ : Tuple = torch.load(UpperCamelCase , map_location="""cpu""" )["""model"""] lowerCamelCase__ : Any = EfficientFormerConfig.from_json_file(UpperCamelCase ) lowerCamelCase__ : List[str] = EfficientFormerForImageClassificationWithTeacher(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = """_""".join(checkpoint_path.split("""/""" )[-1].split(""".""" )[0].split("""_""" )[:-1] ) lowerCamelCase__ : Union[str, Any] = config.depths[-1] - config.num_metaad_blocks + 1 lowerCamelCase__ : str = convert_torch_checkpoint(UpperCamelCase , UpperCamelCase ) model.load_state_dict(UpperCamelCase ) model.eval() lowerCamelCase__ : Any = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } # prepare image lowerCamelCase__ : str = prepare_img() lowerCamelCase__ : Optional[int] = 256 lowerCamelCase__ : List[Any] = 224 lowerCamelCase__ : Union[str, Any] = EfficientFormerImageProcessor( size={"""shortest_edge""": image_size} , crop_size={"""height""": crop_size, """width""": crop_size} , resample=pillow_resamplings["""bicubic"""] , ) lowerCamelCase__ : List[str] = processor(images=UpperCamelCase , return_tensors="""pt""" ).pixel_values # original processing pipeline lowerCamelCase__ : Optional[Any] = Compose( [ Resize(UpperCamelCase , interpolation=pillow_resamplings["""bicubic"""] ), CenterCrop(UpperCamelCase ), ToTensor(), Normalize(UpperCamelCase , UpperCamelCase ), ] ) lowerCamelCase__ : List[str] = image_transforms(UpperCamelCase ).unsqueeze(0 ) assert torch.allclose(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : int = model(UpperCamelCase ) lowerCamelCase__ : Optional[Any] = outputs.logits lowerCamelCase__ : Any = (1, 1000) if "l1" in model_name: lowerCamelCase__ : Optional[Any] = torch.Tensor( [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] ) assert torch.allclose(logits[0, :10] , UpperCamelCase , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: lowerCamelCase__ : List[str] = torch.Tensor( [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] ) assert torch.allclose(logits[0, :10] , UpperCamelCase , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: lowerCamelCase__ : Tuple = torch.Tensor( [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] ) assert logits.shape == expected_shape else: raise ValueError( f'''Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7''' ) # Save Checkpoints Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) model.save_pretrained(UpperCamelCase ) print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) processor.save_pretrained(UpperCamelCase ) print(f'''Processor successfuly saved at {pytorch_dump_path}''' ) if push_to_hub: print("""Pushing model to the hub...""" ) model.push_to_hub( repo_id=f'''Bearnardd/{pytorch_dump_path}''' , commit_message="""Add model""" , use_temp_dir=UpperCamelCase , ) processor.push_to_hub( repo_id=f'''Bearnardd/{pytorch_dump_path}''' , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase , ) if __name__ == "__main__": _A : int =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--pytorch_model_path''', default=None, type=str, required=True, help='''Path to EfficientFormer pytorch checkpoint.''', ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The json file for EfficientFormer model config.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) parser.set_defaults(push_to_hub=True) _A : int =parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
631
'''simple docstring''' from statistics import mean import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : Optional[int] = 0 # Number of processes finished lowerCamelCase__ : Union[str, Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowerCamelCase__ : Tuple = [0] * no_of_process # List to include calculation results lowerCamelCase__ : List[str] = [0] * no_of_process # Sort by arrival time. lowerCamelCase__ : Union[str, Any] = [burst_time[i] for i in np.argsort(UpperCamelCase )] lowerCamelCase__ : List[Any] = [process_name[i] for i in np.argsort(UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: lowerCamelCase__ : str = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowerCamelCase__ : Union[str, Any] = arrival_time[i] lowerCamelCase__ : Any = 0 # Index showing the location of the process being performed lowerCamelCase__ : Union[str, Any] = 0 # Saves the current response ratio. lowerCamelCase__ : Any = 0 for i in range(0 , UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowerCamelCase__ : Optional[int] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowerCamelCase__ : int = temp lowerCamelCase__ : str = i # Calculate the turn around time lowerCamelCase__ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowerCamelCase__ : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : int = [0] * no_of_process for i in range(0 , UpperCamelCase ): lowerCamelCase__ : Optional[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _A : List[str] =5 _A : Optional[Any] =['''A''', '''B''', '''C''', '''D''', '''E'''] _A : Optional[int] =[1, 2, 3, 4, 5] _A : Dict =[1, 2, 3, 4, 5] _A : Any =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _A : Optional[int] =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
631
1
'''simple docstring''' from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand _A : List[str] =logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(UpperCamelCase ): return ext raise Exception( f'''Unable to determine file format from file extension {path}. ''' f'''Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}''' ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Union[str, Any]: lowerCamelCase__ : Dict = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) lowerCamelCase__ : Any = try_infer_format_from_ext(args.input ) if args.format == """infer""" else args.format lowerCamelCase__ : List[str] = PipelineDataFormat.from_str( format=UpperCamelCase , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(UpperCamelCase , UpperCamelCase ) class _lowercase ( _lowercase ): def __init__( self: int , UpperCamelCase__: Pipeline , UpperCamelCase__: PipelineDataFormat ): lowerCamelCase__ : int = nlp lowerCamelCase__ : str = reader @staticmethod def lowerCamelCase_ ( UpperCamelCase__: ArgumentParser ): lowerCamelCase__ : Optional[Any] = parser.add_parser("""run""" , help="""Run a pipeline through the CLI""" ) run_parser.add_argument("""--task""" , choices=get_supported_tasks() , help="""Task to run""" ) run_parser.add_argument("""--input""" , type=UpperCamelCase__ , help="""Path to the file to use for inference""" ) run_parser.add_argument("""--output""" , type=UpperCamelCase__ , help="""Path to the file that will be used post to write results.""" ) run_parser.add_argument("""--model""" , type=UpperCamelCase__ , help="""Name or path to the model to instantiate.""" ) run_parser.add_argument("""--config""" , type=UpperCamelCase__ , help="""Name or path to the model's config to instantiate.""" ) run_parser.add_argument( """--tokenizer""" , type=UpperCamelCase__ , help="""Name of the tokenizer to use. (default: same as the model name)""" ) run_parser.add_argument( """--column""" , type=UpperCamelCase__ , help="""Name of the column to use as input. (For multi columns input as QA use column1,columns2)""" , ) run_parser.add_argument( """--format""" , type=UpperCamelCase__ , default="""infer""" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="""Input format to read from""" , ) run_parser.add_argument( """--device""" , type=UpperCamelCase__ , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) run_parser.add_argument("""--overwrite""" , action="""store_true""" , help="""Allow overwriting the output file.""" ) run_parser.set_defaults(func=UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self._nlp, [] for entry in self._reader: lowerCamelCase__ : Tuple = nlp(**UpperCamelCase__ ) if self._reader.is_multi_columns else nlp(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): outputs.append(UpperCamelCase__ ) else: outputs += output # Saving data if self._nlp.binary_output: lowerCamelCase__ : str = self._reader.save_binary(UpperCamelCase__ ) logger.warning(F'''Current pipeline requires output to be in binary format, saving at {binary_path}''' ) else: self._reader.save(UpperCamelCase__ )
631
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
631
1
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _A : str =(720, 1_280) # Height, Width _A : List[Any] =(0.4, 0.6) # if height or width lower than this scale, drop it. _A : int =1 / 100 _A : List[str] ='''''' _A : Dict ='''''' _A : List[str] ='''''' _A : List[Any] =250 def SCREAMING_SNAKE_CASE_ () -> None: lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = get_dataset(UpperCamelCase , UpperCamelCase ) for index in range(UpperCamelCase ): lowerCamelCase__ : List[str] = random.sample(range(len(UpperCamelCase ) ) , 4 ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = update_image_and_anno( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , filter_scale=UpperCamelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowerCamelCase__ : Any = random_chars(32 ) lowerCamelCase__ : Tuple = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] lowerCamelCase__ : Tuple = f'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(f'''{file_root}.jpg''' , UpperCamelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowerCamelCase__ : Dict = [] for anno in new_annos: lowerCamelCase__ : List[str] = anno[3] - anno[1] lowerCamelCase__ : Any = anno[4] - anno[2] lowerCamelCase__ : Tuple = anno[1] + width / 2 lowerCamelCase__ : Optional[int] = anno[2] + height / 2 lowerCamelCase__ : Union[str, Any] = f'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(UpperCamelCase ) with open(f'''{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> tuple[list, list]: lowerCamelCase__ : Optional[int] = [] lowerCamelCase__ : Tuple = [] for label_file in glob.glob(os.path.join(UpperCamelCase , """*.txt""" ) ): lowerCamelCase__ : int = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(UpperCamelCase ) as in_file: lowerCamelCase__ : Union[str, Any] = in_file.readlines() lowerCamelCase__ : Dict = os.path.join(UpperCamelCase , f'''{label_name}.jpg''' ) lowerCamelCase__ : List[Any] = [] for obj_list in obj_lists: lowerCamelCase__ : Dict = obj_list.rstrip("""\n""" ).split(""" """ ) lowerCamelCase__ : Dict = float(obj[1] ) - float(obj[3] ) / 2 lowerCamelCase__ : List[str] = float(obj[2] ) - float(obj[4] ) / 2 lowerCamelCase__ : Optional[Any] = float(obj[1] ) + float(obj[3] ) / 2 lowerCamelCase__ : List[Any] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(UpperCamelCase ) labels.append(UpperCamelCase ) return img_paths, labels def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = 0.0 , ) -> tuple[list, list, str]: lowerCamelCase__ : str = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowerCamelCase__ : Any = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowerCamelCase__ : Optional[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowerCamelCase__ : List[str] = int(scale_x * output_size[1] ) lowerCamelCase__ : Dict = int(scale_y * output_size[0] ) lowerCamelCase__ : Union[str, Any] = [] lowerCamelCase__ : List[str] = [] for i, index in enumerate(UpperCamelCase ): lowerCamelCase__ : Dict = all_img_list[index] path_list.append(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = all_annos[index] lowerCamelCase__ : List[str] = cva.imread(UpperCamelCase ) if i == 0: # top-left lowerCamelCase__ : Tuple = cva.resize(UpperCamelCase , (divid_point_x, divid_point_y) ) lowerCamelCase__ : Tuple = img for bbox in img_annos: lowerCamelCase__ : Any = bbox[1] * scale_x lowerCamelCase__ : Union[str, Any] = bbox[2] * scale_y lowerCamelCase__ : Union[str, Any] = bbox[3] * scale_x lowerCamelCase__ : Dict = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowerCamelCase__ : Dict = cva.resize(UpperCamelCase , (output_size[1] - divid_point_x, divid_point_y) ) lowerCamelCase__ : Optional[Any] = img for bbox in img_annos: lowerCamelCase__ : Any = scale_x + bbox[1] * (1 - scale_x) lowerCamelCase__ : Tuple = bbox[2] * scale_y lowerCamelCase__ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowerCamelCase__ : Optional[Any] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowerCamelCase__ : Union[str, Any] = cva.resize(UpperCamelCase , (divid_point_x, output_size[0] - divid_point_y) ) lowerCamelCase__ : str = img for bbox in img_annos: lowerCamelCase__ : str = bbox[1] * scale_x lowerCamelCase__ : Any = scale_y + bbox[2] * (1 - scale_y) lowerCamelCase__ : int = bbox[3] * scale_x lowerCamelCase__ : List[str] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowerCamelCase__ : List[Any] = cva.resize( UpperCamelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowerCamelCase__ : str = img for bbox in img_annos: lowerCamelCase__ : List[str] = scale_x + bbox[1] * (1 - scale_x) lowerCamelCase__ : Any = scale_y + bbox[2] * (1 - scale_y) lowerCamelCase__ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowerCamelCase__ : Optional[Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: lowerCamelCase__ : Any = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: assert number_char > 1, "The number of character should greater than 1" lowerCamelCase__ : Optional[int] = ascii_lowercase + digits return "".join(random.choice(UpperCamelCase ) for _ in range(UpperCamelCase ) ) if __name__ == "__main__": main() print('''DONE ✅''')
631
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowercase : def __init__( self: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Optional[int]=30 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: List[str]=3 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=True , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Any=5 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Dict=37 , UpperCamelCase__: List[Any]="gelu" , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: List[Any]=10 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Optional[int]=3 , UpperCamelCase__: Dict=0.6 , UpperCamelCase__: int=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Optional[Any] = patch_size lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Any = is_training lowerCamelCase__ : Union[str, Any] = use_labels lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Any = hidden_dropout_prob lowerCamelCase__ : Optional[int] = attention_probs_dropout_prob lowerCamelCase__ : List[Any] = type_sequence_label_size lowerCamelCase__ : int = initializer_range lowerCamelCase__ : List[str] = mask_ratio lowerCamelCase__ : List[Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowerCamelCase__ : str = (image_size // patch_size) ** 2 lowerCamelCase__ : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: str ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int ): lowerCamelCase__ : Tuple = ViTMAEModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : List[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): lowerCamelCase__ : int = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Any = (self.image_size // self.patch_size) ** 2 lowerCamelCase__ : str = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowerCamelCase__ : Dict = 1 lowerCamelCase__ : Optional[int] = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = config_and_inputs lowerCamelCase__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () a = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} a = False a = False a = False a = False def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Tuple = ViTMAEModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase_ ( self: Dict ): pass def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Any = model_class(UpperCamelCase__ ) lowerCamelCase__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Any = [*signature.parameters.keys()] lowerCamelCase__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] ): # make masks reproducible np.random.seed(2 ) lowerCamelCase__ : Tuple = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) lowerCamelCase__ : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCamelCase__ : Tuple = torch.from_numpy(UpperCamelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowerCamelCase__ : Tuple = pt_noise super().check_pt_tf_models(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Optional[int] = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs[0].cpu().numpy() lowerCamelCase__ : List[str] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model_class.from_pretrained(UpperCamelCase__ ) model.to(UpperCamelCase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) # Make sure we don't have nans lowerCamelCase__ : Dict = after_outputs[0].cpu().numpy() lowerCamelCase__ : Tuple = 0 lowerCamelCase__ : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase__ , 1e-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: Any ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase_ ( self: Tuple ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Optional[int] ): pass @slow def lowerCamelCase_ ( self: List[str] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Tuple = ViTMAEModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> List[Any]: lowerCamelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: List[str] ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self: Tuple ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) lowerCamelCase__ : str = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : int = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowerCamelCase__ : List[str] = ViTMAEConfig() lowerCamelCase__ : int = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowerCamelCase__ : Any = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ , noise=torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ ) ) # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : str = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCamelCase__ ) , atol=1e-4 ) )
631
1
'''simple docstring''' import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class _lowercase ( _lowercase ): a = (PNDMScheduler,) a = (("""num_inference_steps""", 50),) def lowerCamelCase_ ( self: List[str] , **UpperCamelCase__: str ): lowerCamelCase__ : Union[str, Any] = { """num_train_timesteps""": 1_000, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", } config.update(**UpperCamelCase__ ) return config def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: Tuple=0 , **UpperCamelCase__: Tuple ): lowerCamelCase__ : Optional[Any] = dict(self.forward_default_kwargs ) lowerCamelCase__ : Union[str, Any] = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ ) lowerCamelCase__ : Any = self.dummy_sample lowerCamelCase__ : Any = 0.1 * sample lowerCamelCase__ : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: lowerCamelCase__ : List[str] = self.get_scheduler_config(**UpperCamelCase__ ) lowerCamelCase__ : Tuple = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals lowerCamelCase__ : Union[str, Any] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase__ ) lowerCamelCase__ : Tuple = scheduler_class.from_pretrained(UpperCamelCase__ ) new_scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals lowerCamelCase__ : str = dummy_past_residuals[:] lowerCamelCase__ : Union[str, Any] = scheduler.step_prk(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample lowerCamelCase__ : int = new_scheduler.step_prk(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" lowerCamelCase__ : int = scheduler.step_plms(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample lowerCamelCase__ : int = new_scheduler.step_plms(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase_ ( self: List[Any] ): pass def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Any=0 , **UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : List[str] = dict(self.forward_default_kwargs ) lowerCamelCase__ : List[Any] = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ ) lowerCamelCase__ : Any = self.dummy_sample lowerCamelCase__ : int = 0.1 * sample lowerCamelCase__ : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: lowerCamelCase__ : int = self.get_scheduler_config() lowerCamelCase__ : int = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residuals (must be after setting timesteps) lowerCamelCase__ : Union[str, Any] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase__ ) lowerCamelCase__ : int = scheduler_class.from_pretrained(UpperCamelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(UpperCamelCase__ ) # copy over dummy past residual (must be after setting timesteps) lowerCamelCase__ : Optional[int] = dummy_past_residuals[:] lowerCamelCase__ : List[Any] = scheduler.step_prk(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample lowerCamelCase__ : List[Any] = new_scheduler.step_prk(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" lowerCamelCase__ : Tuple = scheduler.step_plms(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample lowerCamelCase__ : Optional[Any] = new_scheduler.step_plms(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCamelCase_ ( self: Any , **UpperCamelCase__: Any ): lowerCamelCase__ : List[Any] = self.scheduler_classes[0] lowerCamelCase__ : Optional[Any] = self.get_scheduler_config(**UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : str = 10 lowerCamelCase__ : Union[str, Any] = self.dummy_model() lowerCamelCase__ : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(UpperCamelCase__ ) for i, t in enumerate(scheduler.prk_timesteps ): lowerCamelCase__ : Tuple = model(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Tuple = scheduler.step_prk(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): lowerCamelCase__ : List[str] = model(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = scheduler.step_plms(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample return sample def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Any = dict(self.forward_default_kwargs ) lowerCamelCase__ : Tuple = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ ) for scheduler_class in self.scheduler_classes: lowerCamelCase__ : int = self.get_scheduler_config() lowerCamelCase__ : List[Any] = scheduler_class(**UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.dummy_sample lowerCamelCase__ : Optional[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(UpperCamelCase__ , """set_timesteps""" ): scheduler.set_timesteps(UpperCamelCase__ ) elif num_inference_steps is not None and not hasattr(UpperCamelCase__ , """set_timesteps""" ): lowerCamelCase__ : List[str] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) lowerCamelCase__ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] lowerCamelCase__ : List[str] = dummy_past_residuals[:] lowerCamelCase__ : Any = scheduler.step_prk(UpperCamelCase__ , 0 , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample lowerCamelCase__ : int = scheduler.step_prk(UpperCamelCase__ , 1 , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) lowerCamelCase__ : Tuple = scheduler.step_plms(UpperCamelCase__ , 0 , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample lowerCamelCase__ : Union[str, Any] = scheduler.step_plms(UpperCamelCase__ , 1 , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase_ ( self: Optional[Any] ): for timesteps in [100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.scheduler_classes[0] lowerCamelCase__ : int = self.get_scheduler_config(steps_offset=1 ) lowerCamelCase__ : Tuple = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def lowerCamelCase_ ( self: List[str] ): for beta_start, beta_end in zip([0.0_001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=UpperCamelCase__ , beta_end=UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): for t in [1, 5, 10]: self.check_over_forward(time_step=UpperCamelCase__ ) def lowerCamelCase_ ( self: int ): for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=UpperCamelCase__ ) def lowerCamelCase_ ( self: int ): # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3 lowerCamelCase__ : int = 27 for scheduler_class in self.scheduler_classes: lowerCamelCase__ : List[str] = self.dummy_sample lowerCamelCase__ : Dict = 0.1 * sample lowerCamelCase__ : Optional[Any] = self.get_scheduler_config() lowerCamelCase__ : Optional[int] = scheduler_class(**UpperCamelCase__ ) scheduler.set_timesteps(UpperCamelCase__ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): lowerCamelCase__ : Any = scheduler.step_prk(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample def lowerCamelCase_ ( self: List[str] ): with self.assertRaises(UpperCamelCase__ ): lowerCamelCase__ : List[str] = self.scheduler_classes[0] lowerCamelCase__ : str = self.get_scheduler_config() lowerCamelCase__ : str = scheduler_class(**UpperCamelCase__ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Union[str, Any] = self.full_loop() lowerCamelCase__ : Optional[Any] = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : Any = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 198.1_318 ) < 1e-2 assert abs(result_mean.item() - 0.2_580 ) < 1e-3 def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Union[str, Any] = self.full_loop(prediction_type="""v_prediction""" ) lowerCamelCase__ : Optional[Any] = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : str = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 67.3_986 ) < 1e-2 assert abs(result_mean.item() - 0.0_878 ) < 1e-3 def lowerCamelCase_ ( self: Optional[Any] ): # We specify different beta, so that the first alpha is 0.99 lowerCamelCase__ : Optional[int] = self.full_loop(set_alpha_to_one=UpperCamelCase__ , beta_start=0.01 ) lowerCamelCase__ : int = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : Dict = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 230.0_399 ) < 1e-2 assert abs(result_mean.item() - 0.2_995 ) < 1e-3 def lowerCamelCase_ ( self: Union[str, Any] ): # We specify different beta, so that the first alpha is 0.99 lowerCamelCase__ : List[str] = self.full_loop(set_alpha_to_one=UpperCamelCase__ , beta_start=0.01 ) lowerCamelCase__ : Union[str, Any] = torch.sum(torch.abs(UpperCamelCase__ ) ) lowerCamelCase__ : Union[str, Any] = torch.mean(torch.abs(UpperCamelCase__ ) ) assert abs(result_sum.item() - 186.9_482 ) < 1e-2 assert abs(result_mean.item() - 0.2_434 ) < 1e-3
631
'''simple docstring''' import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _lowercase ( _lowercase ): a = """""" a = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a = None # compression type in fsspec. ex: "gzip" a = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self: str , UpperCamelCase__: str = "" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , **UpperCamelCase__: List[Any] ): super().__init__(self , **UpperCamelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode lowerCamelCase__ : List[Any] = fsspec.open( UpperCamelCase__ , mode="""rb""" , protocol=UpperCamelCase__ , compression=self.compression , client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) lowerCamelCase__ : str = os.path.basename(self.file.path.split("""::""" )[0] ) lowerCamelCase__ : Union[str, Any] = ( self.compressed_name[: self.compressed_name.rindex(""".""" )] if """.""" in self.compressed_name else self.compressed_name ) lowerCamelCase__ : Tuple = None @classmethod def lowerCamelCase_ ( cls: Optional[int] , UpperCamelCase__: Optional[int] ): # compressed file paths are always relative to the archive root return super()._strip_protocol(UpperCamelCase__ ).lstrip("""/""" ) def lowerCamelCase_ ( self: Tuple ): if self.dir_cache is None: lowerCamelCase__ : Dict = {**self.file.fs.info(self.file.path ), """name""": self.uncompressed_name} lowerCamelCase__ : int = {f["""name"""]: f} def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: str ): return self.file.open().read() def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[int]=None , UpperCamelCase__: Tuple=True , UpperCamelCase__: Tuple=None , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Union[str, Any] = self._strip_protocol(UpperCamelCase__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class _lowercase ( _lowercase ): a = """bz2""" a = """bz2""" a = """.bz2""" class _lowercase ( _lowercase ): a = """gzip""" a = """gzip""" a = """.gz""" class _lowercase ( _lowercase ): a = """lz4""" a = """lz4""" a = """.lz4""" class _lowercase ( _lowercase ): a = """xz""" a = """xz""" a = """.xz""" class _lowercase ( _lowercase ): a = """zstd""" a = """zstd""" a = """.zst""" def __init__( self: int , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , UpperCamelCase__: int = DEFAULT_BLOCK_SIZE , **UpperCamelCase__: Dict , ): super().__init__( fo=UpperCamelCase__ , mode=UpperCamelCase__ , target_protocol=UpperCamelCase__ , target_options=UpperCamelCase__ , block_size=UpperCamelCase__ , **UpperCamelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 lowerCamelCase__ : Tuple = self.file.__enter__ class _lowercase : def __init__( self: Optional[int] , UpperCamelCase__: Any ): lowerCamelCase__ : Optional[int] = file_ def __enter__( self: List[Any] ): self._file.__enter__() return self def __exit__( self: Any , *UpperCamelCase__: str , **UpperCamelCase__: Any ): self._file.__exit__(*UpperCamelCase__ , **UpperCamelCase__ ) def __iter__( self: Any ): return iter(self._file ) def lowerCamelCase_ ( self: List[Any] ): return next(self._file ) def __getattr__( self: List[str] , UpperCamelCase__: Dict ): return getattr(self._file , UpperCamelCase__ ) def fixed_enter(*UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[str] ): return WrappedFile(_enter(*UpperCamelCase__ , **UpperCamelCase__ ) ) lowerCamelCase__ : Optional[Any] = fixed_enter
631
1
'''simple docstring''' import unittest from transformers import AutoTokenizer, FalconConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class _lowercase : def __init__( self: Dict , UpperCamelCase__: str , UpperCamelCase__: Dict=3 , UpperCamelCase__: Union[str, Any]=7 , UpperCamelCase__: Tuple=True , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Any=False , UpperCamelCase__: Any=True , UpperCamelCase__: Tuple=99 , UpperCamelCase__: Optional[Any]=32 , UpperCamelCase__: Any=5 , UpperCamelCase__: Dict=4 , UpperCamelCase__: Dict=37 , UpperCamelCase__: str="gelu" , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: int=512 , UpperCamelCase__: Optional[Any]=16 , UpperCamelCase__: str=2 , UpperCamelCase__: Union[str, Any]=0.02 , UpperCamelCase__: Optional[int]=3 , UpperCamelCase__: Tuple=4 , UpperCamelCase__: Dict=None , ): lowerCamelCase__ : List[Any] = parent lowerCamelCase__ : str = batch_size lowerCamelCase__ : int = seq_length lowerCamelCase__ : Optional[int] = is_training lowerCamelCase__ : int = use_input_mask lowerCamelCase__ : List[Any] = use_token_type_ids lowerCamelCase__ : List[str] = use_labels lowerCamelCase__ : str = vocab_size lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : Optional[int] = num_hidden_layers lowerCamelCase__ : Optional[Any] = num_attention_heads lowerCamelCase__ : Optional[Any] = intermediate_size lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : Tuple = hidden_dropout_prob lowerCamelCase__ : int = attention_probs_dropout_prob lowerCamelCase__ : Any = max_position_embeddings lowerCamelCase__ : Any = type_vocab_size lowerCamelCase__ : str = type_sequence_label_size lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : Any = num_labels lowerCamelCase__ : int = num_choices lowerCamelCase__ : Optional[Any] = scope def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : Tuple = None if self.use_input_mask: lowerCamelCase__ : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : Union[str, Any] = None lowerCamelCase__ : Any = None lowerCamelCase__ : Union[str, Any] = None lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self: Tuple ): return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=UpperCamelCase__ , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : Any = FalconModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ ) lowerCamelCase__ : int = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: Tuple , ): lowerCamelCase__ : Dict = True lowerCamelCase__ : Dict = FalconModel(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Union[str, Any] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , ) lowerCamelCase__ : List[Any] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , ) lowerCamelCase__ : List[Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] , ): lowerCamelCase__ : Any = FalconForCausalLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: int , UpperCamelCase__: Optional[int] , ): lowerCamelCase__ : List[Any] = True lowerCamelCase__ : Dict = True lowerCamelCase__ : str = FalconForCausalLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() # first forward pass lowerCamelCase__ : List[str] = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , use_cache=UpperCamelCase__ , ) lowerCamelCase__ : Optional[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCamelCase__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCamelCase__ : Optional[int] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowerCamelCase__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCamelCase__ : Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 ) lowerCamelCase__ : Tuple = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , output_hidden_states=UpperCamelCase__ , )["""hidden_states"""][0] lowerCamelCase__ : Dict = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , past_key_values=UpperCamelCase__ , output_hidden_states=UpperCamelCase__ , )["""hidden_states"""][0] # select random slice lowerCamelCase__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCamelCase__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() lowerCamelCase__ : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : str = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : List[str] = config_and_inputs lowerCamelCase__ : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): a = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) a = (FalconForCausalLM,) if is_torch_available() else () a = ( { """feature-extraction""": FalconModel, """text-classification""": FalconForSequenceClassification, """text-generation""": FalconForCausalLM, """question-answering""": FalconForQuestionAnswering, """token-classification""": FalconForTokenClassification, """zero-shot""": FalconForSequenceClassification, } if is_torch_available() else {} ) a = False a = False def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Tuple = FalconModelTester(self ) lowerCamelCase__ : Optional[int] = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: Union[str, Any] ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ , *lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: lowerCamelCase__ : str = alibi self.model_tester.create_and_check_model(UpperCamelCase__ , *UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Union[str, Any] = 3 lowerCamelCase__ : Optional[int] = input_dict["""input_ids"""] lowerCamelCase__ : Any = input_ids.ne(1 ).to(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCamelCase__ : Dict = FalconForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : str = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ , lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : int = 3 lowerCamelCase__ : Optional[Any] = """single_label_classification""" lowerCamelCase__ : int = input_dict["""input_ids"""] lowerCamelCase__ : int = input_ids.ne(1 ).to(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCamelCase__ : str = FalconForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ , lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Tuple = input_dict["""input_ids"""] lowerCamelCase__ : Optional[int] = FalconForCausalLM(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = model(UpperCamelCase__ , use_cache=UpperCamelCase__ ) lowerCamelCase__ : str = input_ids.shape[0] lowerCamelCase__ : Dict = model._convert_to_rw_cache(result.past_key_values ) lowerCamelCase__ : str = model._convert_cache_to_standard_format(UpperCamelCase__ , UpperCamelCase__ ) for layer in range(len(UpperCamelCase__ ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ , lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : List[Any] = 3 lowerCamelCase__ : Optional[Any] = """multi_label_classification""" lowerCamelCase__ : List[str] = input_dict["""input_ids"""] lowerCamelCase__ : str = input_ids.ne(1 ).to(UpperCamelCase__ ) lowerCamelCase__ : Tuple = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowerCamelCase__ : Dict = FalconForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Union[str, Any] = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , labels=UpperCamelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase_ ( self: Optional[Any] ): # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(UpperCamelCase__ , """use_cache""" ): return lowerCamelCase__ : List[str] = model_class(UpperCamelCase__ ).to(UpperCamelCase__ ) if "use_cache" not in inputs: lowerCamelCase__ : int = True lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return lowerCamelCase__ : Tuple = ( getattr(UpperCamelCase__ , """decoder_layers""" , UpperCamelCase__ ) or getattr(UpperCamelCase__ , """num_decoder_layers""" , UpperCamelCase__ ) or config.num_hidden_layers ) lowerCamelCase__ : Optional[int] = getattr(UpperCamelCase__ , """num_kv_heads""" , config.num_attention_heads ) lowerCamelCase__ : Tuple = getattr(UpperCamelCase__ , """d_model""" , config.hidden_size ) lowerCamelCase__ : Union[str, Any] = embed_dim // num_attention_heads lowerCamelCase__ : Any = outputs["""past_key_values"""] self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) lowerCamelCase__ , lowerCamelCase__ : Tuple = inputs["""input_ids"""].shape for i in range(UpperCamelCase__ ): if config.new_decoder_architecture: lowerCamelCase__ : Dict = config.num_attention_heads elif config.multi_query: lowerCamelCase__ : List[str] = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class _lowercase ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Union[str, Any] = AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) lowerCamelCase__ : Any = FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) model.eval() model.to(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(UpperCamelCase__ ) lowerCamelCase__ : str = ( """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.""" ) lowerCamelCase__ : List[str] = model.generate(**UpperCamelCase__ , do_sample=UpperCamelCase__ , max_new_tokens=19 ) lowerCamelCase__ : Optional[int] = tokenizer.batch_decode(UpperCamelCase__ )[0] self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: int ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: lowerCamelCase__ : List[Any] = AutoTokenizer.from_pretrained(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = FalconForCausalLM.from_pretrained(UpperCamelCase__ ) model.eval() model.to(UpperCamelCase__ ) lowerCamelCase__ : List[str] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(UpperCamelCase__ ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**UpperCamelCase__ , do_sample=UpperCamelCase__ , max_new_tokens=4 ) model.generate(**UpperCamelCase__ , do_sample=UpperCamelCase__ , max_new_tokens=4 ) model.generate(**UpperCamelCase__ , num_beams=2 , max_new_tokens=4 ) @slow def lowerCamelCase_ ( self: str ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: lowerCamelCase__ : Union[str, Any] = AutoTokenizer.from_pretrained(UpperCamelCase__ ) lowerCamelCase__ : str = FalconForCausalLM.from_pretrained(UpperCamelCase__ ) model.eval() model.to(device=UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(UpperCamelCase__ ) # Test results are the same with and without cache lowerCamelCase__ : Union[str, Any] = model.generate(**UpperCamelCase__ , do_sample=UpperCamelCase__ , max_new_tokens=20 , use_cache=UpperCamelCase__ ) lowerCamelCase__ : str = model.generate(**UpperCamelCase__ , do_sample=UpperCamelCase__ , max_new_tokens=20 , use_cache=UpperCamelCase__ ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
631
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() _A : int =logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: print("""Loading config file...""" ) def flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase="" , UpperCamelCase="." ): lowerCamelCase__ : Optional[int] = [] for k, v in d.items(): lowerCamelCase__ : Optional[int] = parent_key + sep + k if parent_key else k if isinstance(UpperCamelCase , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase , sep=UpperCamelCase ).items() ) else: items.append((new_key, v) ) return dict(UpperCamelCase ) lowerCamelCase__ : Any = argparse.Namespace() with open(UpperCamelCase , """r""" ) as yaml_file: try: lowerCamelCase__ : int = yaml.load(UpperCamelCase , Loader=yaml.FullLoader ) lowerCamelCase__ : Tuple = flatten_yaml_as_dict(UpperCamelCase ) for k, v in flat_cfg.items(): setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) except yaml.YAMLError as exc: logger.error("""Error while loading config file: {}. Error message: {}""".format(UpperCamelCase , str(UpperCamelCase ) ) ) return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Union[str, Any] = MobileViTVaConfig() lowerCamelCase__ : str = False # dataset if task_name.startswith("""imagenet1k_""" ): lowerCamelCase__ : Optional[Any] = 1000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : int = 384 else: lowerCamelCase__ : Optional[int] = 256 lowerCamelCase__ : str = """imagenet-1k-id2label.json""" elif task_name.startswith("""imagenet21k_to_1k_""" ): lowerCamelCase__ : Tuple = 21000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : str = 384 else: lowerCamelCase__ : Any = 256 lowerCamelCase__ : int = """imagenet-22k-id2label.json""" elif task_name.startswith("""ade20k_""" ): lowerCamelCase__ : Dict = 151 lowerCamelCase__ : str = 512 lowerCamelCase__ : List[Any] = """ade20k-id2label.json""" lowerCamelCase__ : Union[str, Any] = True elif task_name.startswith("""voc_""" ): lowerCamelCase__ : Tuple = 21 lowerCamelCase__ : Optional[int] = 512 lowerCamelCase__ : List[Any] = """pascal-voc-id2label.json""" lowerCamelCase__ : Tuple = True # orig_config lowerCamelCase__ : Optional[int] = load_orig_config_file(UpperCamelCase ) assert getattr(UpperCamelCase , """model.classification.name""" , -1 ) == "mobilevit_v2", "Invalid model" lowerCamelCase__ : int = getattr(UpperCamelCase , """model.classification.mitv2.width_multiplier""" , 1.0 ) assert ( getattr(UpperCamelCase , """model.classification.mitv2.attn_norm_layer""" , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.classification.activation.name""" , """swish""" ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: lowerCamelCase__ : Any = getattr(UpperCamelCase , """model.segmentation.output_stride""" , 16 ) if "_deeplabv3" in task_name: lowerCamelCase__ : str = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_rates""" , [12, 24, 36] ) lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_out_channels""" , 512 ) lowerCamelCase__ : List[Any] = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_dropout""" , 0.1 ) # id2label lowerCamelCase__ : Tuple = """huggingface/label-files""" lowerCamelCase__ : Optional[Any] = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase__ : Union[str, Any] = {int(UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : int = idalabel lowerCamelCase__ : Optional[Any] = {v: k for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any: lowerCamelCase__ : List[Any] = dct.pop(UpperCamelCase ) lowerCamelCase__ : Dict = val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> Tuple: if base_model: lowerCamelCase__ : Optional[int] = """""" else: lowerCamelCase__ : Optional[Any] = """mobilevitv2.""" lowerCamelCase__ : List[str] = [] for k in state_dict.keys(): if k[:8] == "encoder.": lowerCamelCase__ : Optional[Any] = k[8:] else: lowerCamelCase__ : Optional[Any] = k if ".block." in k: lowerCamelCase__ : Dict = k_new.replace(""".block.""" , """.""" ) if ".conv." in k: lowerCamelCase__ : List[Any] = k_new.replace(""".conv.""" , """.convolution.""" ) if ".norm." in k: lowerCamelCase__ : str = k_new.replace(""".norm.""" , """.normalization.""" ) if "conv_1." in k: lowerCamelCase__ : Any = k_new.replace("""conv_1.""" , f'''{model_prefix}conv_stem.''' ) for i in [1, 2]: if f'''layer_{i}.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.''' , f'''{model_prefix}encoder.layer.{i-1}.layer.''' ) if ".exp_1x1." in k: lowerCamelCase__ : Dict = k_new.replace(""".exp_1x1.""" , """.expand_1x1.""" ) if ".red_1x1." in k: lowerCamelCase__ : str = k_new.replace(""".red_1x1.""" , """.reduce_1x1.""" ) for i in [3, 4, 5]: if f'''layer_{i}.0.''' in k: lowerCamelCase__ : List[str] = k_new.replace(f'''layer_{i}.0.''' , f'''{model_prefix}encoder.layer.{i-1}.downsampling_layer.''' ) if f'''layer_{i}.1.local_rep.0.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.1.local_rep.0.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_kxk.''' ) if f'''layer_{i}.1.local_rep.1.''' in k: lowerCamelCase__ : Dict = k_new.replace(f'''layer_{i}.1.local_rep.1.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_1x1.''' ) for i in [3, 4, 5]: if i == 3: lowerCamelCase__ : int = [0, 1] elif i == 4: lowerCamelCase__ : str = [0, 1, 2, 3] elif i == 5: lowerCamelCase__ : Dict = [0, 1, 2] for j in j_in: if f'''layer_{i}.1.global_rep.{j}.''' in k: lowerCamelCase__ : List[Any] = k_new.replace( f'''layer_{i}.1.global_rep.{j}.''' , f'''{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.''' ) if f'''layer_{i}.1.global_rep.{j+1}.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace( f'''layer_{i}.1.global_rep.{j+1}.''' , f'''{model_prefix}encoder.layer.{i-1}.layernorm.''' ) if f'''layer_{i}.1.conv_proj.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace(f'''layer_{i}.1.conv_proj.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_projection.''' ) if "pre_norm_attn.0." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.0.""" , """layernorm_before.""" ) if "pre_norm_attn.1." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.1.""" , """attention.""" ) if "pre_norm_ffn.0." in k: lowerCamelCase__ : Optional[Any] = k_new.replace("""pre_norm_ffn.0.""" , """layernorm_after.""" ) if "pre_norm_ffn.1." in k: lowerCamelCase__ : Union[str, Any] = k_new.replace("""pre_norm_ffn.1.""" , """ffn.conv1.""" ) if "pre_norm_ffn.3." in k: lowerCamelCase__ : List[Any] = k_new.replace("""pre_norm_ffn.3.""" , """ffn.conv2.""" ) if "classifier.1." in k: lowerCamelCase__ : Tuple = k_new.replace("""classifier.1.""" , """classifier.""" ) if "seg_head." in k: lowerCamelCase__ : Optional[int] = k_new.replace("""seg_head.""" , """segmentation_head.""" ) if ".aspp_layer." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_pool.""" , """.""" ) rename_keys.append((k, k_new) ) return rename_keys def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: lowerCamelCase__ : Union[str, Any] = [] for k in state_dict.keys(): if k.startswith("""seg_head.aux_head.""" ): keys_to_ignore.append(UpperCamelCase ) for k in keys_to_ignore: state_dict.pop(UpperCamelCase , UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Dict: lowerCamelCase__ : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" lowerCamelCase__ : Tuple = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCamelCase__ : str = get_mobilevitva_config(UpperCamelCase , UpperCamelCase ) # load original state_dict lowerCamelCase__ : List[str] = torch.load(UpperCamelCase , map_location="""cpu""" ) # load huggingface model if task_name.startswith("""ade20k_""" ) or task_name.startswith("""voc_""" ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation(UpperCamelCase ).eval() lowerCamelCase__ : Tuple = False else: lowerCamelCase__ : int = MobileViTVaForImageClassification(UpperCamelCase ).eval() lowerCamelCase__ : Optional[Any] = False # remove and rename some keys of load the original model lowerCamelCase__ : Tuple = checkpoint remove_unused_keys(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = create_rename_keys(UpperCamelCase , base_model=UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # load modified state_dict model.load_state_dict(UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor lowerCamelCase__ : int = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) lowerCamelCase__ : Dict = image_processor(images=prepare_img() , return_tensors="""pt""" ) lowerCamelCase__ : str = model(**UpperCamelCase ) # verify classification model if task_name.startswith("""imagenet""" ): lowerCamelCase__ : Dict = outputs.logits lowerCamelCase__ : Optional[Any] = logits.argmax(-1 ).item() print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] ) if task_name.startswith("""imagenet1k_256""" ) and config.width_multiplier == 1.0: # expected_logits for base variant lowerCamelCase__ : Optional[Any] = torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01] ) assert torch.allclose(logits[0, :3] , UpperCamelCase , atol=1E-4 ) Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(f'''Saving model {task_name} 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 __name__ == "__main__": _A : Optional[int] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''imagenet1k_256''', type=str, help=( '''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ''' ''' Classification (ImageNet-1k) - MobileViTV2 (256x256) : imagenet1k_256 - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384 - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) : imagenet21k_to_1k_256 - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on ImageNet-1k 384x384) : imagenet21k_to_1k_384 Segmentation - ADE20K Dataset : ade20k_deeplabv3 - Pascal VOC 2012 Dataset: voc_deeplabv3 ''' ), choices=[ '''imagenet1k_256''', '''imagenet1k_384''', '''imagenet21k_to_1k_256''', '''imagenet21k_to_1k_384''', '''ade20k_deeplabv3''', '''voc_deeplabv3''', ], ) parser.add_argument( '''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) _A : Dict =parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
631
1
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys _A : Dict ='''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
631
'''simple docstring''' import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _lowercase ( _lowercase ): def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCamelCase__ , """width_multiplier""" ) ) class _lowercase : def __init__( self: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: str=13 , UpperCamelCase__: Any=64 , UpperCamelCase__: Optional[Any]=2 , UpperCamelCase__: str=3 , UpperCamelCase__: List[str]="swish" , UpperCamelCase__: Any=3 , UpperCamelCase__: Optional[int]=32 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: int=0.02 , UpperCamelCase__: Dict=True , UpperCamelCase__: Dict=True , UpperCamelCase__: Any=10 , UpperCamelCase__: int=None , UpperCamelCase__: List[Any]=0.25 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Optional[int]=0.0 , ): lowerCamelCase__ : Any = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : str = patch_size lowerCamelCase__ : Optional[int] = num_channels lowerCamelCase__ : Optional[Any] = make_divisible(512 * width_multiplier , divisor=8 ) lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : Any = conv_kernel_size lowerCamelCase__ : Any = output_stride lowerCamelCase__ : Union[str, Any] = classifier_dropout_prob lowerCamelCase__ : List[str] = use_labels lowerCamelCase__ : Optional[Any] = is_training lowerCamelCase__ : List[str] = num_labels lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[Any] = scope lowerCamelCase__ : Tuple = width_multiplier lowerCamelCase__ : List[Any] = ffn_dropout lowerCamelCase__ : Any = attn_dropout def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Tuple = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase__ : str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCamelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCamelCase_ ( self: List[Any] ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Union[str, Any] = MobileViTVaModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : str = model(UpperCamelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : Tuple = self.num_labels lowerCamelCase__ : Dict = MobileViTVaForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str ): lowerCamelCase__ : List[str] = self.num_labels lowerCamelCase__ : Union[str, Any] = MobileViTVaForSemanticSegmentation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase__ : List[Any] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Any = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) a = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) a = False a = False a = False a = False def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = MobileViTVaModelTester(self ) lowerCamelCase__ : List[str] = MobileViTVaConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def lowerCamelCase_ ( self: Union[str, Any] ): pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Tuple ): pass def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ , lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Tuple = [*signature.parameters.keys()] lowerCamelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): def check_hidden_states_output(UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs.hidden_states lowerCamelCase__ : List[Any] = 5 self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase__ : int = 2 for i in range(len(UpperCamelCase__ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCamelCase__ , lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : int = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__ : str = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Union[str, Any] = MobileViTVaModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> Optional[int]: lowerCamelCase__ : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: Tuple ): return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[Any] = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = self.default_image_processor lowerCamelCase__ : List[Any] = prepare_img() lowerCamelCase__ : Any = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : int = model(**UpperCamelCase__ ) # verify the logits lowerCamelCase__ : str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Any = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Union[str, Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Optional[Any] = model(**UpperCamelCase__ ) lowerCamelCase__ : str = outputs.logits # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Any = torch.tensor( [ [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]], [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]], [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]], ] , device=UpperCamelCase__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Optional[Any] = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : List[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Dict = model(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = outputs.logits.detach().cpu() lowerCamelCase__ : List[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ , target_sizes=[(50, 60)] ) lowerCamelCase__ : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ ) lowerCamelCase__ : int = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ )
631
1
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Optional[int] =logging.get_logger(__name__) _A : List[Any] ={ '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """xlm-prophetnet""" a = ["""past_key_values"""] a = { """num_attention_heads""": """num_encoder_attention_heads""", } def __init__( self: Union[str, Any] , UpperCamelCase__: Optional[float] = 0.1 , UpperCamelCase__: Optional[Union[str, Callable]] = "gelu" , UpperCamelCase__: Optional[int] = 30_522 , UpperCamelCase__: Optional[int] = 1_024 , UpperCamelCase__: Optional[int] = 4_096 , UpperCamelCase__: Optional[int] = 12 , UpperCamelCase__: Optional[int] = 16 , UpperCamelCase__: Optional[int] = 4_096 , UpperCamelCase__: Optional[int] = 12 , UpperCamelCase__: Optional[int] = 16 , UpperCamelCase__: Optional[float] = 0.1 , UpperCamelCase__: Optional[float] = 0.1 , UpperCamelCase__: Optional[int] = 512 , UpperCamelCase__: Optional[float] = 0.02 , UpperCamelCase__: Optional[bool] = True , UpperCamelCase__: Optional[bool] = True , UpperCamelCase__: Optional[int] = 0 , UpperCamelCase__: Optional[int] = 2 , UpperCamelCase__: Optional[int] = 32 , UpperCamelCase__: Optional[int] = 128 , UpperCamelCase__: Optional[bool] = False , UpperCamelCase__: Optional[float] = 0.0 , UpperCamelCase__: Optional[bool] = True , UpperCamelCase__: Optional[int] = 0 , UpperCamelCase__: Optional[int] = 1 , UpperCamelCase__: Optional[int] = 2 , **UpperCamelCase__: Any , ): lowerCamelCase__ : Union[str, Any] = vocab_size lowerCamelCase__ : str = hidden_size lowerCamelCase__ : List[Any] = encoder_ffn_dim lowerCamelCase__ : Optional[int] = num_encoder_layers lowerCamelCase__ : List[str] = num_encoder_attention_heads lowerCamelCase__ : Dict = decoder_ffn_dim lowerCamelCase__ : Optional[Any] = num_decoder_layers lowerCamelCase__ : List[Any] = num_decoder_attention_heads lowerCamelCase__ : str = max_position_embeddings lowerCamelCase__ : Optional[int] = init_std # Normal(0, this parameter) lowerCamelCase__ : Dict = activation_function # parameters for xlmprophetnet lowerCamelCase__ : Dict = ngram lowerCamelCase__ : Any = num_buckets lowerCamelCase__ : int = relative_max_distance lowerCamelCase__ : Optional[int] = disable_ngram_loss lowerCamelCase__ : int = eps # 3 Types of Dropout lowerCamelCase__ : str = attention_dropout lowerCamelCase__ : Dict = activation_dropout lowerCamelCase__ : str = dropout lowerCamelCase__ : List[Any] = use_cache super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) @property def lowerCamelCase_ ( self: Union[str, Any] ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: Dict ): raise NotImplementedError( """This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and""" """ `num_decoder_layers`.""" )
631
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _A : Optional[Any] =logging.get_logger(__name__) _A : Dict ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _A : Tuple ={ '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } _A : List[Any] ={ '''gpt-neox-20b''': 2_048, } class _lowercase ( _lowercase ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["""input_ids""", """attention_mask"""] def __init__( self: Optional[int] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: int=None , UpperCamelCase__: Tuple=None , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Union[str, Any]="<|endoftext|>" , UpperCamelCase__: Tuple=False , **UpperCamelCase__: str , ): super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , **UpperCamelCase__ , ) lowerCamelCase__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: lowerCamelCase__ : Any = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) ) lowerCamelCase__ : Dict = add_prefix_space lowerCamelCase__ : Optional[int] = pre_tok_class(**UpperCamelCase__ ) lowerCamelCase__ : Dict = add_prefix_space def lowerCamelCase_ ( self: int , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): lowerCamelCase__ : Optional[Any] = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: "Conversation" ): lowerCamelCase__ : str = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [self.eos_token_id] ) if len(UpperCamelCase__ ) > self.model_max_length: lowerCamelCase__ : int = input_ids[-self.model_max_length :] return input_ids
631
1
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class _lowercase : a = 42 # [batch_size x 3] a = 42 # [batch_size x 3] a = 42 # [batch_size x 3] a = 42 # [batch_size x 3] a = 42 a = 42 a = 42 a = 42 a = 42 def lowerCamelCase_ ( self: str ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def lowerCamelCase_ ( self: Optional[int] ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def lowerCamelCase_ ( self: List[Any] ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Tuple = torch.arange(self.height * self.width ) lowerCamelCase__ : List[str] = torch.stack( [ pixel_indices % self.width, torch.div(UpperCamelCase__ , self.width , rounding_mode="""trunc""" ), ] , axis=1 , ) return coords @property def lowerCamelCase_ ( self: Any ): lowerCamelCase__ , *lowerCamelCase__ : Any = self.shape lowerCamelCase__ : Optional[Any] = int(np.prod(UpperCamelCase__ ) ) lowerCamelCase__ : Union[str, Any] = self.get_image_coords() lowerCamelCase__ : List[str] = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) lowerCamelCase__ : str = self.get_camera_rays(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = rays.view(UpperCamelCase__ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def lowerCamelCase_ ( self: int , UpperCamelCase__: torch.Tensor ): lowerCamelCase__ , *lowerCamelCase__ , lowerCamelCase__ : Optional[int] = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] lowerCamelCase__ : List[str] = coords.view(UpperCamelCase__ , -1 , 2 ) lowerCamelCase__ : Optional[int] = self.resolution() lowerCamelCase__ : Optional[Any] = self.fov() lowerCamelCase__ : Optional[Any] = (flat.float() / (res - 1)) * 2 - 1 lowerCamelCase__ : Dict = fracs * torch.tan(fov / 2 ) lowerCamelCase__ : Union[str, Any] = fracs.view(UpperCamelCase__ , -1 , 2 ) lowerCamelCase__ : Tuple = ( self.z.view(UpperCamelCase__ , 1 , 3 ) + self.x.view(UpperCamelCase__ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(UpperCamelCase__ , 1 , 3 ) * fracs[:, :, 1:] ) lowerCamelCase__ : str = directions / directions.norm(dim=-1 , keepdim=UpperCamelCase__ ) lowerCamelCase__ : Dict = torch.stack( [ torch.broadcast_to(self.origin.view(UpperCamelCase__ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(UpperCamelCase__ , *UpperCamelCase__ , 2 , 3 ) def lowerCamelCase_ ( self: str , UpperCamelCase__: int , UpperCamelCase__: int ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=UpperCamelCase__ , height=UpperCamelCase__ , x_fov=self.x_fov , y_fov=self.y_fov , ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> DifferentiableProjectiveCamera: lowerCamelCase__ : Optional[int] = [] lowerCamelCase__ : Union[str, Any] = [] lowerCamelCase__ : Dict = [] lowerCamelCase__ : List[Any] = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): lowerCamelCase__ : List[str] = np.array([np.sin(UpperCamelCase ), np.cos(UpperCamelCase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) lowerCamelCase__ : Any = -z * 4 lowerCamelCase__ : int = np.array([np.cos(UpperCamelCase ), -np.sin(UpperCamelCase ), 0.0] ) lowerCamelCase__ : List[Any] = np.cross(UpperCamelCase , UpperCamelCase ) origins.append(UpperCamelCase ) xs.append(UpperCamelCase ) ys.append(UpperCamelCase ) zs.append(UpperCamelCase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(UpperCamelCase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(UpperCamelCase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(UpperCamelCase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(UpperCamelCase , axis=0 ) ).float() , width=UpperCamelCase , height=UpperCamelCase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(UpperCamelCase )) , )
631
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A : Dict ={ '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class _lowercase : def __init__( self: Optional[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: int=13 , UpperCamelCase__: List[str]=7 , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: Any=True , UpperCamelCase__: List[str]=True , UpperCamelCase__: Optional[Any]=99 , UpperCamelCase__: Union[str, Any]=32 , UpperCamelCase__: Optional[Any]=5 , UpperCamelCase__: str=4 , UpperCamelCase__: str=37 , UpperCamelCase__: List[str]="gelu" , UpperCamelCase__: Any=0.1 , UpperCamelCase__: Any=0.1 , UpperCamelCase__: Optional[Any]=512 , UpperCamelCase__: Dict=16 , UpperCamelCase__: Union[str, Any]=2 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Union[str, Any]=3 , UpperCamelCase__: Optional[int]=4 , UpperCamelCase__: Any=None , ): lowerCamelCase__ : str = parent lowerCamelCase__ : Any = batch_size lowerCamelCase__ : Optional[int] = seq_length lowerCamelCase__ : List[str] = is_training lowerCamelCase__ : str = use_token_type_ids lowerCamelCase__ : List[Any] = use_labels lowerCamelCase__ : str = vocab_size lowerCamelCase__ : str = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : Union[str, Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : Union[str, Any] = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Any = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = max_position_embeddings lowerCamelCase__ : int = type_vocab_size lowerCamelCase__ : Any = type_sequence_label_size lowerCamelCase__ : Optional[Any] = initializer_range lowerCamelCase__ : Union[str, Any] = num_labels lowerCamelCase__ : str = num_choices lowerCamelCase__ : int = scope lowerCamelCase__ : Dict = self.vocab_size - 1 def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : List[Any] = None if self.use_token_type_ids: lowerCamelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : List[Any] = None lowerCamelCase__ : Tuple = None lowerCamelCase__ : int = None if self.use_labels: lowerCamelCase__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : int = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) lowerCamelCase__ : Any = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict , *UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : int = OpenAIGPTModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Union[str, Any] = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , head_mask=UpperCamelCase__ ) lowerCamelCase__ : str = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) lowerCamelCase__ : str = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , *UpperCamelCase__: int ): lowerCamelCase__ : str = OpenAIGPTLMHeadModel(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Any = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Dict , UpperCamelCase__: str , *UpperCamelCase__: int ): lowerCamelCase__ : List[str] = OpenAIGPTDoubleHeadsModel(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: Dict , *UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : List[Any] = self.num_labels lowerCamelCase__ : int = OpenAIGPTForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : List[Any] = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : Union[str, Any] = config_and_inputs lowerCamelCase__ : Dict = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask, } return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): a = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) a = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly a = ( { """feature-extraction""": OpenAIGPTModel, """text-classification""": OpenAIGPTForSequenceClassification, """text-generation""": OpenAIGPTLMHeadModel, """zero-shot""": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: int ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def lowerCamelCase_ ( self: Dict , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: List[str]=False ): lowerCamelCase__ : Tuple = super()._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": lowerCamelCase__ : Dict = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=UpperCamelCase__ , ) lowerCamelCase__ : Optional[int] = inputs_dict["""labels"""] lowerCamelCase__ : Tuple = inputs_dict["""labels"""] lowerCamelCase__ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=UpperCamelCase__ , ) lowerCamelCase__ : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ ) return inputs_dict def lowerCamelCase_ ( self: str ): lowerCamelCase__ : str = OpenAIGPTModelTester(self ) lowerCamelCase__ : str = ConfigTester(self , config_class=UpperCamelCase__ , n_embd=37 ) def lowerCamelCase_ ( self: Dict ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: int ): lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: int ): for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Union[str, Any] = OpenAIGPTModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class _lowercase ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Union[str, Any] = OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" ) model.to(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = torch.tensor([[481, 4_735, 544]] , dtype=torch.long , device=UpperCamelCase__ ) # the president is lowerCamelCase__ : Optional[Any] = [ 481, 4_735, 544, 246, 963, 870, 762, 239, 244, 40_477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the lowerCamelCase__ : Optional[int] = model.generate(UpperCamelCase__ , do_sample=UpperCamelCase__ ) self.assertListEqual(output_ids[0].tolist() , UpperCamelCase__ )
631
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin _A : int =get_tests_dir('''fixtures/test_sentencepiece.model''') _A : Tuple ={'''target_lang''': '''fi''', '''source_lang''': '''en'''} _A : int ='''>>zh<<''' _A : Dict ='''Helsinki-NLP/''' if is_torch_available(): _A : List[Any] ='''pt''' elif is_tf_available(): _A : Optional[int] ='''tf''' else: _A : Dict ='''jax''' @require_sentencepiece class _lowercase ( _lowercase , unittest.TestCase ): a = MarianTokenizer a = False a = True def lowerCamelCase_ ( self: List[str] ): super().setUp() lowerCamelCase__ : List[Any] = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] lowerCamelCase__ : Optional[Any] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) lowerCamelCase__ : Optional[int] = Path(self.tmpdirname ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) lowerCamelCase__ : Dict = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self: Optional[Any] , **UpperCamelCase__: Any ): return MarianTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] ): return ( "This is a test", "This is a test", ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Any = """</s>""" lowerCamelCase__ : List[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__ ) , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(UpperCamelCase__ ) , 9 ) def lowerCamelCase_ ( self: int ): self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def lowerCamelCase_ ( self: int ): lowerCamelCase__ : List[Any] = MarianTokenizer.from_pretrained(F'''{ORG_NAME}opus-mt-en-de''' ) lowerCamelCase__ : Optional[int] = en_de_tokenizer(["""I am a small frog"""] , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [38, 121, 14, 697, 38_848, 0] self.assertListEqual(UpperCamelCase__ , batch.input_ids[0] ) lowerCamelCase__ : List[str] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : Tuple = [x.name for x in Path(UpperCamelCase__ ).glob("""*""" )] self.assertIn("""source.spm""" , UpperCamelCase__ ) MarianTokenizer.from_pretrained(UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : List[Any] = self.get_tokenizer() lowerCamelCase__ : Any = tok( ["""I am a small frog""" * 1_000, """I am a small frog"""] , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Dict = tok(["""I am a tiny frog""", """I am a small frog"""] , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def lowerCamelCase_ ( self: List[str] ): # fmt: off lowerCamelCase__ : int = {"""input_ids""": [[43_495, 462, 20, 42_164, 1_369, 52, 464, 132, 1_703, 492, 13, 7_491, 38_999, 6, 8, 464, 132, 1_703, 492, 13, 4_669, 37_867, 13, 7_525, 27, 1_593, 988, 13, 33_972, 7_029, 6, 20, 8_251, 383, 2, 270, 5_866, 3_788, 2, 2_353, 8_251, 12_338, 2, 13_958, 387, 2, 3_629, 6_953, 188, 2_900, 2, 13_958, 8_011, 11_501, 23, 8_460, 4_073, 34_009, 20, 435, 11_439, 27, 8, 8_460, 4_073, 6_004, 20, 9_988, 375, 27, 33, 266, 1_945, 1_076, 1_350, 37_867, 3_288, 5, 577, 1_076, 4_374, 8, 5_082, 5, 26_453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10_767, 6, 316, 304, 4_239, 3, 0], [148, 15_722, 19, 1_839, 12, 1_350, 13, 22_327, 5_082, 5_418, 47_567, 35_938, 59, 318, 19_552, 108, 2_183, 54, 14_976, 4_835, 32, 547, 1_114, 8, 315, 2_417, 5, 92, 19_088, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100], [36, 6_395, 12_570, 39_147, 11_597, 6, 266, 4, 45_405, 7_296, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase__ , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Union[str, Any] = MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) lowerCamelCase__ : str = """Tämä on testi""" lowerCamelCase__ : Any = """This is a test""" lowerCamelCase__ : int = [76, 7, 2_047, 2] lowerCamelCase__ : List[str] = [69, 12, 11, 940, 2] lowerCamelCase__ : Tuple = tokenizer(UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = tokenizer(text_target=UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Tuple = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
631
1
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _A : Optional[int] =10 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> int: for i in range(UpperCamelCase , UpperCamelCase ): if array[i] == target: return i return -1 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: lowerCamelCase__ : Optional[Any] = 0 lowerCamelCase__ : Dict = len(UpperCamelCase ) while left <= right: if right - left < precision: return lin_search(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : int = (left + right) // 3 + 1 lowerCamelCase__ : Dict = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: lowerCamelCase__ : Dict = one_third - 1 elif array[two_third] < target: lowerCamelCase__ : Union[str, Any] = two_third + 1 else: lowerCamelCase__ : Any = one_third + 1 lowerCamelCase__ : Optional[Any] = two_third - 1 else: return -1 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> int: if left < right: if right - left < precision: return lin_search(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Dict = (left + right) // 3 + 1 lowerCamelCase__ : int = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(UpperCamelCase , one_third - 1 , UpperCamelCase , UpperCamelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , UpperCamelCase , UpperCamelCase , UpperCamelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , UpperCamelCase , UpperCamelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() _A : Tuple =input('''Enter numbers separated by comma:\n''').strip() _A : Any =[int(item.strip()) for item in user_input.split(''',''')] assert collection == sorted(collection), F"List must be ordered.\n{collection}." _A : List[str] =int(input('''Enter the number to be found in the list:\n''').strip()) _A : Optional[int] =ite_ternary_search(collection, target) _A : List[Any] =rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F'Iterative search: {target} found at positions: {resulta}') print(F'Recursive search: {target} found at positions: {resulta}') else: print('''Not found''')
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Optional[Any] =logging.get_logger(__name__) _A : Optional[int] ={ '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """rwkv""" a = {"""max_position_embeddings""": """context_length"""} def __init__( self: Tuple , UpperCamelCase__: Optional[Any]=50_277 , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Tuple=4_096 , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Dict=None , UpperCamelCase__: Dict=None , UpperCamelCase__: int=1e-5 , UpperCamelCase__: Any=0 , UpperCamelCase__: str=0 , UpperCamelCase__: Union[str, Any]=6 , UpperCamelCase__: Optional[int]=False , UpperCamelCase__: Dict=True , **UpperCamelCase__: Dict , ): lowerCamelCase__ : Dict = vocab_size lowerCamelCase__ : Optional[Any] = context_length lowerCamelCase__ : Optional[Any] = hidden_size lowerCamelCase__ : Any = num_hidden_layers lowerCamelCase__ : int = attention_hidden_size if attention_hidden_size is not None else hidden_size lowerCamelCase__ : Union[str, Any] = intermediate_size if intermediate_size is not None else 4 * hidden_size lowerCamelCase__ : List[str] = layer_norm_epsilon lowerCamelCase__ : int = rescale_every lowerCamelCase__ : Optional[int] = use_cache lowerCamelCase__ : Dict = bos_token_id lowerCamelCase__ : Any = eos_token_id super().__init__( tie_word_embeddings=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: lowerCamelCase__ : int = [1] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = 0, 0, 0 lowerCamelCase__ : Optional[int] = ugly_nums[ia] * 2 lowerCamelCase__ : List[str] = ugly_nums[ia] * 3 lowerCamelCase__ : str = ugly_nums[ia] * 5 for _ in range(1 , UpperCamelCase ): lowerCamelCase__ : List[str] = min(UpperCamelCase , UpperCamelCase , UpperCamelCase ) ugly_nums.append(UpperCamelCase ) if next_num == next_a: ia += 1 lowerCamelCase__ : str = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 lowerCamelCase__ : Optional[int] = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 lowerCamelCase__ : Optional[Any] = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F'{ugly_numbers(200) = }')
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str =logging.get_logger(__name__) _A : int ={ '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """roc_bert""" def __init__( self: Optional[Any] , UpperCamelCase__: Any=30_522 , UpperCamelCase__: Optional[Any]=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: Tuple=12 , UpperCamelCase__: Tuple=3_072 , UpperCamelCase__: str="gelu" , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Dict=512 , UpperCamelCase__: str=2 , UpperCamelCase__: str=0.02 , UpperCamelCase__: Tuple=1e-12 , UpperCamelCase__: Any=True , UpperCamelCase__: Union[str, Any]=0 , UpperCamelCase__: List[Any]="absolute" , UpperCamelCase__: Any=None , UpperCamelCase__: Any=True , UpperCamelCase__: Optional[int]=True , UpperCamelCase__: Union[str, Any]=768 , UpperCamelCase__: int=910 , UpperCamelCase__: Tuple=512 , UpperCamelCase__: int=24_858 , UpperCamelCase__: Optional[Any]=True , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : Tuple = num_attention_heads lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : List[Any] = use_cache lowerCamelCase__ : Tuple = enable_pronunciation lowerCamelCase__ : Union[str, Any] = enable_shape lowerCamelCase__ : Union[str, Any] = pronunciation_embed_dim lowerCamelCase__ : Any = pronunciation_vocab_size lowerCamelCase__ : int = shape_embed_dim lowerCamelCase__ : Tuple = shape_vocab_size lowerCamelCase__ : Optional[Any] = concat_input lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Dict = classifier_dropout super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: # Return True if there is node that has not iterated. lowerCamelCase__ : Dict = [False] * len(UpperCamelCase ) lowerCamelCase__ : Optional[int] = [] queue.append(UpperCamelCase ) lowerCamelCase__ : Dict = True while queue: lowerCamelCase__ : List[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(UpperCamelCase ) lowerCamelCase__ : Tuple = True lowerCamelCase__ : int = u return visited[t] def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[Any]: # This array is filled by BFS and to store path lowerCamelCase__ : List[str] = [-1] * (len(UpperCamelCase )) lowerCamelCase__ : str = 0 while bfs(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : Dict = float("""Inf""" ) lowerCamelCase__ : Union[str, Any] = sink while s != source: # Find the minimum value in select path lowerCamelCase__ : Union[str, Any] = min(UpperCamelCase , graph[parent[s]][s] ) lowerCamelCase__ : Optional[Any] = parent[s] max_flow += path_flow lowerCamelCase__ : Any = sink while v != source: lowerCamelCase__ : str = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow lowerCamelCase__ : Dict = parent[v] return max_flow _A : Optional[int] =[ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _A , _A : List[Any] =0, 5 print(ford_fulkerson(graph, source, sink))
631
'''simple docstring''' import sys import turtle def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> None: my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( '''Correct format for using this script: ''' '''python fractals.py <int:depth_for_fractal>''' ) _A : Any =turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('''red''') _A : Dict =[(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 10 , UpperCamelCase = 1000 , UpperCamelCase = True ) -> int: assert ( isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("""Invalid value for min_val or max_val (min_value < max_value)""" ) return min_val if option else max_val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: return int((number_a + number_a) / 2 ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> None: assert ( isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("""argument value for lower and higher must be(lower > higher)""" ) if not lower < to_guess < higher: raise ValueError( """guess value must be within the range of lower and higher value""" ) def answer(UpperCamelCase ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("""started...""" ) lowerCamelCase__ : Any = lower lowerCamelCase__ : Any = higher lowerCamelCase__ : List[Any] = [] while True: lowerCamelCase__ : Dict = get_avg(UpperCamelCase , UpperCamelCase ) last_numbers.append(UpperCamelCase ) if answer(UpperCamelCase ) == "low": lowerCamelCase__ : List[str] = number elif answer(UpperCamelCase ) == "high": lowerCamelCase__ : Union[str, Any] = number else: break print(f'''guess the number : {last_numbers[-1]}''' ) print(f'''details : {last_numbers!s}''' ) def SCREAMING_SNAKE_CASE_ () -> None: lowerCamelCase__ : Optional[int] = int(input("""Enter lower value : """ ).strip() ) lowerCamelCase__ : Any = int(input("""Enter high value : """ ).strip() ) lowerCamelCase__ : Any = int(input("""Enter value to guess : """ ).strip() ) guess_the_number(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if __name__ == "__main__": main()
631
'''simple docstring''' from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class _lowercase : def __init__( self: int , UpperCamelCase__: Dict , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Union[str, Any]=7 , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: List[Any]=True , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: int=True , UpperCamelCase__: List[Any]=99 , UpperCamelCase__: Tuple=32 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Optional[int]=37 , UpperCamelCase__: Any="gelu" , UpperCamelCase__: Any=0.1 , UpperCamelCase__: int=0.1 , UpperCamelCase__: Optional[Any]=512 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Tuple=3 , UpperCamelCase__: Optional[int]=4 , UpperCamelCase__: Union[str, Any]=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Union[str, Any] = 13 lowerCamelCase__ : Any = 7 lowerCamelCase__ : int = True lowerCamelCase__ : Optional[Any] = True lowerCamelCase__ : Dict = True lowerCamelCase__ : List[str] = True lowerCamelCase__ : str = 99 lowerCamelCase__ : Dict = 384 lowerCamelCase__ : Optional[Any] = 2 lowerCamelCase__ : Optional[int] = 4 lowerCamelCase__ : Optional[Any] = 37 lowerCamelCase__ : Union[str, Any] = """gelu""" lowerCamelCase__ : int = 0.1 lowerCamelCase__ : Optional[Any] = 0.1 lowerCamelCase__ : List[Any] = 512 lowerCamelCase__ : Optional[Any] = 16 lowerCamelCase__ : Any = 2 lowerCamelCase__ : Optional[Any] = 0.02 lowerCamelCase__ : int = 3 lowerCamelCase__ : List[str] = 4 lowerCamelCase__ : Any = 128 lowerCamelCase__ : List[Any] = 2 lowerCamelCase__ : Optional[Any] = 9 lowerCamelCase__ : Any = 1 lowerCamelCase__ : Optional[int] = None def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : str = None if self.use_input_mask: lowerCamelCase__ : int = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : List[str] = None if self.use_token_type_ids: lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : int = None lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Any = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : List[Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCamelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: Any ): lowerCamelCase__ : List[Any] = TFConvBertModel(config=UpperCamelCase__ ) lowerCamelCase__ : str = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase__ : List[str] = [input_ids, input_mask] lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: Tuple , UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : int = TFConvBertForMaskedLM(config=UpperCamelCase__ ) lowerCamelCase__ : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : int = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : int = self.num_labels lowerCamelCase__ : Dict = TFConvBertForSequenceClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: Dict ): lowerCamelCase__ : Optional[int] = self.num_choices lowerCamelCase__ : Dict = TFConvBertForMultipleChoice(config=UpperCamelCase__ ) lowerCamelCase__ : int = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : List[str] = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Any = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Tuple = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Any , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: int ): lowerCamelCase__ : List[Any] = self.num_labels lowerCamelCase__ : List[str] = TFConvBertForTokenClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Optional[int] = TFConvBertForQuestionAnswering(config=UpperCamelCase__ ) lowerCamelCase__ : int = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : str = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : str = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a = ( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a = False a = False a = False def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Dict = TFConvBertModelTester(self ) lowerCamelCase__ : Dict = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: List[str] ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Dict = True lowerCamelCase__ : Tuple = True if hasattr(UpperCamelCase__ , """use_cache""" ): lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : List[str] = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Tuple = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) for model_class in self.all_model_classes: lowerCamelCase__ : int = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : Dict = len(model(UpperCamelCase__ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ , saved_model=UpperCamelCase__ ) lowerCamelCase__ : int = os.path.join(UpperCamelCase__ , """saved_model""" , """1""" ) lowerCamelCase__ : List[Any] = tf.keras.models.load_model(UpperCamelCase__ ) lowerCamelCase__ : Any = model(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : Dict = outputs["""encoder_hidden_states"""] lowerCamelCase__ : Any = outputs["""encoder_attentions"""] else: lowerCamelCase__ : int = outputs["""hidden_states"""] lowerCamelCase__ : Optional[int] = outputs["""attentions"""] self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Union[str, Any] = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) self.assertIsNotNone(UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : int = getattr(self.model_tester , """decoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Any = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Optional[int] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) def check_decoder_attentions_output(UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) self.assertEqual(out_len % 2 , 0 ) lowerCamelCase__ : Any = outputs.decoder_attentions self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(UpperCamelCase__: List[str] ): lowerCamelCase__ : Any = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: lowerCamelCase__ : int = True lowerCamelCase__ : Any = False lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = len(UpperCamelCase__ ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) lowerCamelCase__ : Tuple = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_decoder_attentions_output(UpperCamelCase__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Dict = model_class(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) # Check attention is always last and order is fine lowerCamelCase__ : List[Any] = True lowerCamelCase__ : int = True lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCamelCase__ ) ) self.assertEqual(model.config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) @require_tf class _lowercase ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) lowerCamelCase__ : Optional[Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ )[0] lowerCamelCase__ : Dict = [1, 6, 768] self.assertEqual(output.shape , UpperCamelCase__ ) lowerCamelCase__ : Dict = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCamelCase__ , atol=1e-4 )
631
1
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets _A : int =datasets.logging.get_logger(__name__) _A : Any ='''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' _A : Optional[int] ='''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' _A : Tuple =''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' _A : Optional[Any] ={ '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def lowerCamelCase_ ( self: Union[str, Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/google-research/bleurt""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/bleurt"""] , reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""] , ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: Dict ): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( """Using default BLEURT-Base checkpoint for sequence maximum length 128. """ """You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').""" ) lowerCamelCase__ : str = """bleurt-base-128""" if self.config_name.lower() in CHECKPOINT_URLS: lowerCamelCase__ : int = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: lowerCamelCase__ : List[Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer lowerCamelCase__ : Union[str, Any] = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) lowerCamelCase__ : Optional[int] = score.BleurtScorer(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: Any ): lowerCamelCase__ : int = self.scorer.score(references=UpperCamelCase__ , candidates=UpperCamelCase__ ) return {"scores": scores}
631
'''simple docstring''' _A : List[str] ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
631
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Optional[int] =logging.get_logger(__name__) _A : Tuple ={ '''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """git_vision_model""" def __init__( self: Any , UpperCamelCase__: str=768 , UpperCamelCase__: str=3_072 , UpperCamelCase__: Any=12 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Tuple=3 , UpperCamelCase__: List[Any]=224 , UpperCamelCase__: int=16 , UpperCamelCase__: Dict="quick_gelu" , UpperCamelCase__: Tuple=1e-5 , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Union[str, Any]=0.02 , **UpperCamelCase__: List[str] , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = hidden_size lowerCamelCase__ : List[Any] = intermediate_size lowerCamelCase__ : Union[str, Any] = num_hidden_layers lowerCamelCase__ : Any = num_attention_heads lowerCamelCase__ : Dict = num_channels lowerCamelCase__ : List[Any] = patch_size lowerCamelCase__ : Any = image_size lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[str] = attention_dropout lowerCamelCase__ : Union[str, Any] = layer_norm_eps lowerCamelCase__ : str = hidden_act @classmethod def lowerCamelCase_ ( cls: Dict , UpperCamelCase__: Union[str, os.PathLike] , **UpperCamelCase__: List[str] ): cls._set_token_in_kwargs(UpperCamelCase__ ) lowerCamelCase__ , lowerCamelCase__ : Dict = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": lowerCamelCase__ : int = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ ) class _lowercase ( _lowercase ): a = """git""" def __init__( self: Dict , UpperCamelCase__: Dict=None , UpperCamelCase__: int=30_522 , UpperCamelCase__: Optional[int]=768 , UpperCamelCase__: Tuple=6 , UpperCamelCase__: int=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: str="gelu" , UpperCamelCase__: Any=0.1 , UpperCamelCase__: Optional[int]=0.1 , UpperCamelCase__: Optional[int]=1_024 , UpperCamelCase__: Any=0.02 , UpperCamelCase__: Union[str, Any]=1e-12 , UpperCamelCase__: Dict=0 , UpperCamelCase__: Any="absolute" , UpperCamelCase__: Dict=True , UpperCamelCase__: Any=False , UpperCamelCase__: List[Any]=101 , UpperCamelCase__: Union[str, Any]=102 , UpperCamelCase__: Union[str, Any]=None , **UpperCamelCase__: Optional[Any] , ): super().__init__(bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) if vision_config is None: lowerCamelCase__ : List[str] = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) lowerCamelCase__ : Optional[int] = GitVisionConfig(**UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = vocab_size lowerCamelCase__ : Optional[Any] = hidden_size lowerCamelCase__ : Any = num_hidden_layers lowerCamelCase__ : Optional[Any] = num_attention_heads lowerCamelCase__ : Union[str, Any] = hidden_act lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : Union[str, Any] = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : str = max_position_embeddings lowerCamelCase__ : Optional[Any] = initializer_range lowerCamelCase__ : Optional[int] = layer_norm_eps lowerCamelCase__ : Optional[Any] = position_embedding_type lowerCamelCase__ : Optional[int] = use_cache lowerCamelCase__ : int = tie_word_embeddings lowerCamelCase__ : int = num_image_with_embedding lowerCamelCase__ : Union[str, Any] = bos_token_id lowerCamelCase__ : Union[str, Any] = eos_token_id def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Optional[Any] = copy.deepcopy(self.__dict__ ) lowerCamelCase__ : Union[str, Any] = self.vision_config.to_dict() lowerCamelCase__ : Optional[Any] = self.__class__.model_type return output
631
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Any =logging.get_logger(__name__) _A : Dict ={ '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class _lowercase ( _lowercase ): a = """trocr""" a = ["""past_key_values"""] a = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Optional[Any] , UpperCamelCase__: int=50_265 , UpperCamelCase__: int=1_024 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Dict=16 , UpperCamelCase__: int=4_096 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: int=512 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Any=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: str=True , UpperCamelCase__: Tuple=False , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Tuple=True , UpperCamelCase__: Dict=1 , UpperCamelCase__: List[str]=0 , UpperCamelCase__: Union[str, Any]=2 , **UpperCamelCase__: str , ): lowerCamelCase__ : Any = vocab_size lowerCamelCase__ : Tuple = d_model lowerCamelCase__ : Any = decoder_layers lowerCamelCase__ : Dict = decoder_attention_heads lowerCamelCase__ : str = decoder_ffn_dim lowerCamelCase__ : Tuple = activation_function lowerCamelCase__ : Dict = max_position_embeddings lowerCamelCase__ : int = dropout lowerCamelCase__ : int = attention_dropout lowerCamelCase__ : List[Any] = activation_dropout lowerCamelCase__ : Union[str, Any] = init_std lowerCamelCase__ : Optional[int] = decoder_layerdrop lowerCamelCase__ : Dict = use_cache lowerCamelCase__ : Any = scale_embedding lowerCamelCase__ : Optional[int] = use_learned_position_embeddings lowerCamelCase__ : List[str] = layernorm_embedding super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
631
1
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer _A : Optional[int] =logging.get_logger(__name__) _A : Tuple ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _A : Any ={ '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } _A : List[str] ={'''allegro/herbert-base-cased''': 514} _A : Tuple ={} class _lowercase ( _lowercase ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_INIT_CONFIGURATION a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = HerbertTokenizer def __init__( self: Tuple , UpperCamelCase__: Dict=None , UpperCamelCase__: Any=None , UpperCamelCase__: Optional[Any]=None , UpperCamelCase__: List[Any]="<s>" , UpperCamelCase__: Any="<unk>" , UpperCamelCase__: Any="<pad>" , UpperCamelCase__: Dict="<mask>" , UpperCamelCase__: Any="</s>" , **UpperCamelCase__: int , ): super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , cls_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , **UpperCamelCase__ , ) def lowerCamelCase_ ( self: int , UpperCamelCase__: List[int] , UpperCamelCase__: Optional[List[int]] = None ): lowerCamelCase__ : List[Any] = [self.cls_token_id] lowerCamelCase__ : str = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase_ ( self: str , UpperCamelCase__: List[int] , UpperCamelCase__: Optional[List[int]] = None , UpperCamelCase__: bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase__ )) + [1] return [1] + ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1] def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: List[int] , UpperCamelCase__: Optional[List[int]] = None ): lowerCamelCase__ : str = [self.sep_token_id] lowerCamelCase__ : 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 ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): lowerCamelCase__ : Tuple = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ )
631
'''simple docstring''' # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : str = [False] * len(UpperCamelCase ) lowerCamelCase__ : str = [-1] * len(UpperCamelCase ) def dfs(UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Union[str, Any] = c for u in graph[v]: if not visited[u]: dfs(UpperCamelCase , 1 - c ) for i in range(len(UpperCamelCase ) ): if not visited[i]: dfs(UpperCamelCase , 0 ) for i in range(len(UpperCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph _A : int ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
631
1
'''simple docstring''' from math import factorial, pi def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase = 30 ) -> float: if not isinstance(UpperCamelCase , (int, float) ): raise ValueError("""maclaurin_sin() requires either an int or float for theta""" ) if not isinstance(UpperCamelCase , UpperCamelCase ) or accuracy <= 0: raise ValueError("""maclaurin_sin() requires a positive int for accuracy""" ) lowerCamelCase__ : List[str] = float(UpperCamelCase ) lowerCamelCase__ : str = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(UpperCamelCase ) ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase = 30 ) -> float: if not isinstance(UpperCamelCase , (int, float) ): raise ValueError("""maclaurin_cos() requires either an int or float for theta""" ) if not isinstance(UpperCamelCase , UpperCamelCase ) or accuracy <= 0: raise ValueError("""maclaurin_cos() requires a positive int for accuracy""" ) lowerCamelCase__ : Optional[int] = float(UpperCamelCase ) lowerCamelCase__ : Optional[int] = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(UpperCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
631
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Optional[int] = dataset lowerCamelCase__ : Optional[int] = process lowerCamelCase__ : List[str] = params def __len__( self: List[str] ): return len(self.dataset ) def __getitem__( self: Any , UpperCamelCase__: int ): lowerCamelCase__ : Dict = self.dataset[i] lowerCamelCase__ : Union[str, Any] = self.process(UpperCamelCase__ , **self.params ) return processed class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): lowerCamelCase__ : int = loader lowerCamelCase__ : str = infer lowerCamelCase__ : Optional[int] = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : int = loader_batch_size # Internal bookkeeping lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None def __len__( self: Dict ): return len(self.loader ) def __iter__( self: Optional[int] ): lowerCamelCase__ : List[Any] = iter(self.loader ) return self def lowerCamelCase_ ( self: Any ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowerCamelCase__ : str = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowerCamelCase__ : int = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first lowerCamelCase__ : str = element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : Tuple = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : List[str] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : int = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowerCamelCase__ : List[str] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : Optional[Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : int = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowerCamelCase__ : str = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowerCamelCase__ : Optional[int] = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def lowerCamelCase_ ( self: List[Any] ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowerCamelCase__ : Optional[Any] = next(self.iterator ) lowerCamelCase__ : List[str] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Optional[Any] = processed else: lowerCamelCase__ : Union[str, Any] = list(processed.keys() )[0] lowerCamelCase__ : Any = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Any = len(UpperCamelCase__ ) else: lowerCamelCase__ : List[str] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : Union[str, Any] = observed_batch_size # Setting internal index to unwrap the batch lowerCamelCase__ : List[Any] = processed lowerCamelCase__ : List[Any] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class _lowercase ( _lowercase ): def __init__( self: List[str] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any]=None ): super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self: Union[str, Any] ): lowerCamelCase__ : str = iter(self.loader ) lowerCamelCase__ : int = None return self def lowerCamelCase_ ( self: str ): if self.subiterator is None: lowerCamelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowerCamelCase__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowerCamelCase__ : Any = self.infer(next(self.iterator ) , **self.params ) lowerCamelCase__ : Union[str, Any] = next(self.subiterator ) return processed class _lowercase ( _lowercase ): def __iter__( self: List[Any] ): lowerCamelCase__ : int = iter(self.loader ) return self def lowerCamelCase_ ( self: Tuple ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowerCamelCase__ : List[str] = False lowerCamelCase__ : Union[str, Any] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : Any = self.loader_batch_item() lowerCamelCase__ : Tuple = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: lowerCamelCase__ : str = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Dict = processed else: lowerCamelCase__ : Dict = list(processed.keys() )[0] lowerCamelCase__ : Dict = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) else: lowerCamelCase__ : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : str = observed_batch_size lowerCamelCase__ : str = processed lowerCamelCase__ : Optional[int] = 0 while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : List[Any] = self.loader_batch_item() lowerCamelCase__ : str = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: lowerCamelCase__ : Optional[Any] = processed lowerCamelCase__ : Optional[int] = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) return accumulator class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str ): lowerCamelCase__ : Union[str, Any] = dataset lowerCamelCase__ : str = key def __len__( self: Optional[Any] ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Any ): return self.dataset[i][self.key] class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str , UpperCamelCase__: str ): lowerCamelCase__ : str = dataset lowerCamelCase__ : Dict = keya lowerCamelCase__ : List[str] = keya def __len__( self: str ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Union[str, Any] ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
631
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase = False ) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3317044064679887385961981 and not allow_probable: raise ValueError( """Warning: upper bound of deterministic test is exceeded. """ """Pass allow_probable=True to allow probabilistic test. """ """A return value of True indicates a probable prime.""" ) # array bounds provided by analysis lowerCamelCase__ : str = [ 2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 1, 3825123056546413051, 1, 1, 318665857834031151167461, 3317044064679887385961981, ] lowerCamelCase__ : Tuple = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(SCREAMING_SNAKE_CASE_ , 1 ): if n < _p: # then we have our last prime to check lowerCamelCase__ : Optional[int] = primes[:idx] break lowerCamelCase__ , lowerCamelCase__ : Tuple = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: lowerCamelCase__ : List[Any] = False for r in range(SCREAMING_SNAKE_CASE_ ): lowerCamelCase__ : List[Any] = pow(SCREAMING_SNAKE_CASE_ , d * 2**r , SCREAMING_SNAKE_CASE_ ) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): lowerCamelCase__ : Union[str, Any] = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def SCREAMING_SNAKE_CASE_ () -> None: assert not miller_rabin(561 ) assert miller_rabin(563 ) # 2047 assert not miller_rabin(838201 ) assert miller_rabin(838207 ) # 1_373_653 assert not miller_rabin(17316001 ) assert miller_rabin(17316017 ) # 25_326_001 assert not miller_rabin(3078386641 ) assert miller_rabin(3078386653 ) # 3_215_031_751 assert not miller_rabin(1713045574801 ) assert miller_rabin(1713045574819 ) # 2_152_302_898_747 assert not miller_rabin(2779799728307 ) assert miller_rabin(2779799728327 ) # 3_474_749_660_383 assert not miller_rabin(113850023909441 ) assert miller_rabin(113850023909527 ) # 341_550_071_728_321 assert not miller_rabin(1275041018848804351 ) assert miller_rabin(1275041018848804391 ) # 3_825_123_056_546_413_051 assert not miller_rabin(79666464458507787791867 ) assert miller_rabin(79666464458507787791951 ) # 318_665_857_834_031_151_167_461 assert not miller_rabin(552840677446647897660333 ) assert miller_rabin(552840677446647897660359 ) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
700
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys _A : Dict ='''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
631
0
'''simple docstring''' from PIL import Image def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Union[str, Any]: lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = image.size lowerCamelCase__ : int = 0 lowerCamelCase__ : Optional[Any] = image.load() for i in range(__A ): for j in range(__A ): lowerCamelCase__ : int = pixels[j, i] mean += pixel mean //= width * height for j in range(__A ): for i in range(__A ): lowerCamelCase__ : Any = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": _A : int =mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
701
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _A : Any ={ '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : str =[ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
0
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Dict =logging.get_logger(__name__) _A : Union[str, Any] ={ 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class _lowercase ( snake_case__ ): a = """encodec""" def __init__( self: Optional[Any] , UpperCamelCase__: int=[1.5, 3.0, 6.0, 12.0, 24.0] , UpperCamelCase__: Dict=24_000 , UpperCamelCase__: List[str]=1 , UpperCamelCase__: Tuple=False , UpperCamelCase__: Tuple=None , UpperCamelCase__: Optional[Any]=None , UpperCamelCase__: Dict=128 , UpperCamelCase__: int=32 , UpperCamelCase__: Tuple=1 , UpperCamelCase__: Any=[8, 5, 4, 2] , UpperCamelCase__: Union[str, Any]="weight_norm" , UpperCamelCase__: Dict=7 , UpperCamelCase__: str=7 , UpperCamelCase__: int=3 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: List[Any]=True , UpperCamelCase__: Tuple="reflect" , UpperCamelCase__: List[Any]=2 , UpperCamelCase__: Dict=2 , UpperCamelCase__: Union[str, Any]=1.0 , UpperCamelCase__: List[str]=1_024 , UpperCamelCase__: int=None , UpperCamelCase__: str=True , **UpperCamelCase__: str , ): lowerCamelCase__ : Tuple = target_bandwidths lowerCamelCase__ : Optional[int] = sampling_rate lowerCamelCase__ : Dict = audio_channels lowerCamelCase__ : Optional[int] = normalize lowerCamelCase__ : Union[str, Any] = chunk_length_s lowerCamelCase__ : List[Any] = overlap lowerCamelCase__ : str = hidden_size lowerCamelCase__ : int = num_filters lowerCamelCase__ : Tuple = num_residual_layers lowerCamelCase__ : Any = upsampling_ratios lowerCamelCase__ : Optional[Any] = norm_type lowerCamelCase__ : Optional[Any] = kernel_size lowerCamelCase__ : str = last_kernel_size lowerCamelCase__ : Any = residual_kernel_size lowerCamelCase__ : Union[str, Any] = dilation_growth_rate lowerCamelCase__ : Tuple = use_causal_conv lowerCamelCase__ : Tuple = pad_mode lowerCamelCase__ : int = compress lowerCamelCase__ : Tuple = num_lstm_layers lowerCamelCase__ : Dict = trim_right_ratio lowerCamelCase__ : str = codebook_size lowerCamelCase__ : str = codebook_dim if codebook_dim is not None else hidden_size lowerCamelCase__ : str = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F'''self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}''' ) super().__init__(**UpperCAmelCase_ ) @property def lowerCamelCase_ ( self: List[Any] ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def lowerCamelCase_ ( self: str ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Any = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def lowerCamelCase_ ( self: Optional[Any] ): return int(1_000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
702
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : List[str] ={ '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """audio-spectrogram-transformer""" def __init__( self: str , UpperCamelCase__: Any=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: List[Any]=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: Optional[Any]="gelu" , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: Union[str, Any]=0.02 , UpperCamelCase__: Dict=1e-12 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=10 , UpperCamelCase__: List[str]=10 , UpperCamelCase__: Any=1_024 , UpperCamelCase__: Optional[Any]=128 , **UpperCamelCase__: Union[str, Any] , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : List[str] = num_attention_heads lowerCamelCase__ : Optional[int] = intermediate_size lowerCamelCase__ : List[Any] = hidden_act lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : str = attention_probs_dropout_prob lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[str] = layer_norm_eps lowerCamelCase__ : List[Any] = patch_size lowerCamelCase__ : List[str] = qkv_bias lowerCamelCase__ : Dict = frequency_stride lowerCamelCase__ : List[Any] = time_stride lowerCamelCase__ : str = max_length lowerCamelCase__ : Dict = num_mel_bins
631
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): a = StableDiffusionXLImgaImgPipeline a = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} a = PipelineTesterMixin.required_optional_params - {"latents"} a = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS a = IMAGE_TO_IMAGE_IMAGE_PARAMS a = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase_ ( self: str ): torch.manual_seed(0 ) lowerCamelCase__ : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=A_ , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) lowerCamelCase__ : Optional[Any] = EulerDiscreteScheduler( beta_start=0.00_085 , beta_end=0.012 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) lowerCamelCase__ : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowerCamelCase__ : Optional[Any] = 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=1_000 , hidden_act="""gelu""" , projection_dim=32 , ) lowerCamelCase__ : List[str] = CLIPTextModel(A_ ) lowerCamelCase__ : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=A_ ) lowerCamelCase__ : str = CLIPTextModelWithProjection(A_ ) lowerCamelCase__ : str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=A_ ) lowerCamelCase__ : Union[str, Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def lowerCamelCase_ ( self: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple=0 ): lowerCamelCase__ : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(A_ ) ).to(A_ ) lowerCamelCase__ : List[str] = image / 2 + 0.5 if str(A_ ).startswith("""mps""" ): lowerCamelCase__ : List[str] = torch.manual_seed(A_ ) else: lowerCamelCase__ : Any = torch.Generator(device=A_ ).manual_seed(A_ ) lowerCamelCase__ : Any = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.75, } return inputs def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : Tuple = self.get_dummy_components() lowerCamelCase__ : Dict = StableDiffusionXLImgaImgPipeline(**A_ ) lowerCamelCase__ : Dict = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) lowerCamelCase__ : List[str] = self.get_dummy_inputs(A_ ) lowerCamelCase__ : List[Any] = sd_pipe(**A_ ).images lowerCamelCase__ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCamelCase__ : Optional[int] = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCamelCase_ ( self: Union[str, Any] ): super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def lowerCamelCase_ ( self: Any ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowerCamelCase_ ( self: Tuple ): pass def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Dict = self.get_dummy_components() lowerCamelCase__ : List[Any] = StableDiffusionXLImgaImgPipeline(**A_ ) lowerCamelCase__ : int = sd_pipe.to(A_ ) lowerCamelCase__ : Optional[Any] = sd_pipe.to(A_ ) sd_pipe.set_progress_bar_config(disable=A_ ) # forward without prompt embeds lowerCamelCase__ : List[Any] = self.get_dummy_inputs(A_ ) lowerCamelCase__ : str = 3 * ["""this is a negative prompt"""] lowerCamelCase__ : Tuple = negative_prompt lowerCamelCase__ : Union[str, Any] = 3 * [inputs["""prompt"""]] lowerCamelCase__ : Optional[int] = sd_pipe(**A_ ) lowerCamelCase__ : List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCamelCase__ : List[Any] = self.get_dummy_inputs(A_ ) lowerCamelCase__ : Optional[int] = 3 * ["""this is a negative prompt"""] lowerCamelCase__ : Optional[Any] = 3 * [inputs.pop("""prompt""" )] ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : str = sd_pipe.encode_prompt(A_ , negative_prompt=A_ ) lowerCamelCase__ : List[str] = sd_pipe( **A_ , prompt_embeds=A_ , negative_prompt_embeds=A_ , pooled_prompt_embeds=A_ , negative_pooled_prompt_embeds=A_ , ) lowerCamelCase__ : List[Any] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @slow @require_torch_gpu class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: str ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase_ ( self: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int]="cpu" , UpperCamelCase__: List[Any]=torch.floataa , UpperCamelCase__: List[Any]=0 ): lowerCamelCase__ : Optional[Any] = torch.Generator(device=A_ ).manual_seed(A_ ) lowerCamelCase__ : Optional[Any] = np.random.RandomState(A_ ).standard_normal((1, 4, 64, 64) ) lowerCamelCase__ : Optional[Any] = torch.from_numpy(A_ ).to(device=A_ , dtype=A_ ) lowerCamelCase__ : Optional[int] = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : List[str] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) lowerCamelCase__ : List[str] = self.get_inputs(A_ ) lowerCamelCase__ : List[str] = pipe(**A_ ).images lowerCamelCase__ : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) lowerCamelCase__ : Union[str, Any] = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506] ) assert np.abs(image_slice - expected_slice ).max() < 7e-3
703
'''simple docstring''' import argparse import os import re import packaging.version _A : List[str] ='''examples/''' _A : Any ={ '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } _A : int ={ '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } _A : int ='''README.md''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> str: with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : List[str] = f.read() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = REPLACE_PATTERNS[pattern] lowerCamelCase__ : Dict = replace.replace("""VERSION""" , UpperCamelCase ) lowerCamelCase__ : str = re_pattern.sub(UpperCamelCase , UpperCamelCase ) with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: for folder, directories, fnames in os.walk(UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(UpperCamelCase , UpperCamelCase ) , UpperCamelCase , pattern="""examples""" ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> List[Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if not patch: update_version_in_examples(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: lowerCamelCase__ : Dict = """🤗 Transformers currently provides the following architectures""" lowerCamelCase__ : Dict = """1. Want to contribute a new model?""" with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : int = f.readlines() # Find the start of the list. lowerCamelCase__ : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowerCamelCase__ : Optional[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): lowerCamelCase__ : List[Any] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: lowerCamelCase__ : int = f.read() lowerCamelCase__ : Optional[Any] = REPLACE_PATTERNS["""init"""][0].search(UpperCamelCase ).groups()[0] return packaging.version.parse(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase=False ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: lowerCamelCase__ : List[str] = default_version.base_version elif patch: lowerCamelCase__ : Any = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowerCamelCase__ : List[Any] = f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowerCamelCase__ : Any = input(f'''Which version are you releasing? [{default_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Optional[int] = default_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase , patch=UpperCamelCase ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def SCREAMING_SNAKE_CASE_ () -> List[str]: lowerCamelCase__ : Optional[int] = get_version() lowerCamelCase__ : Any = f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowerCamelCase__ : Any = current_version.base_version # Check with the user we got that right. lowerCamelCase__ : List[Any] = input(f'''Which version are we developing now? [{dev_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Dict = dev_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') _A : List[str] =parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
631
0
'''simple docstring''' from collections.abc import Callable import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> np.ndarray: lowerCamelCase__ : Optional[Any] = int(np.ceil((x_end - xa) / step_size ) ) lowerCamelCase__ : int = np.zeros((n + 1,) ) lowerCamelCase__ : Optional[int] = ya lowerCamelCase__ : int = xa for k in range(_lowercase ): lowerCamelCase__ : List[Any] = y[k] + step_size * ode_func(_lowercase , y[k] ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
704
'''simple docstring''' import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow _A : Union[str, Any] =False class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: Dict , UpperCamelCase__: str=32 ): set_seed(0 ) lowerCamelCase__ : Optional[int] = UNetaDModel(sample_size=UpperCamelCase__ , in_channels=3 , out_channels=3 ) lowerCamelCase__ : List[Any] = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Optional[Any] = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCamelCase__ : List[Any] = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) lowerCamelCase__ : Any = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCamelCase__ : str = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randn((4, 3, 32, 32) ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randint(0 , 1_000 , (4,) ).long().to(UpperCamelCase__ ) for _ in range(4 )] # train with a DDPM scheduler lowerCamelCase__ , lowerCamelCase__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : str = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : str = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Tuple = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : Dict = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Union[str, Any] = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) )
631
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class _lowercase : a = MBartConfig a = {} a = """gelu""" def __init__( self: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Dict=13 , UpperCamelCase__: Tuple=7 , UpperCamelCase__: str=True , UpperCamelCase__: Optional[Any]=False , UpperCamelCase__: Union[str, Any]=99 , UpperCamelCase__: Dict=32 , UpperCamelCase__: Any=2 , UpperCamelCase__: Tuple=4 , UpperCamelCase__: List[Any]=37 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: Any=0.1 , UpperCamelCase__: List[Any]=20 , UpperCamelCase__: Dict=2 , UpperCamelCase__: str=1 , UpperCamelCase__: Dict=0 , ): lowerCamelCase__ : Optional[int] = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = seq_length lowerCamelCase__ : Dict = is_training lowerCamelCase__ : Dict = use_labels lowerCamelCase__ : List[Any] = vocab_size lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : str = num_attention_heads lowerCamelCase__ : int = intermediate_size lowerCamelCase__ : List[str] = hidden_dropout_prob lowerCamelCase__ : str = attention_probs_dropout_prob lowerCamelCase__ : Optional[int] = max_position_embeddings lowerCamelCase__ : str = eos_token_id lowerCamelCase__ : Any = pad_token_id lowerCamelCase__ : List[str] = bos_token_id def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCamelCase__ : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCamelCase__ : Any = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : Dict = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowerCamelCase__ : Any = prepare_mbart_inputs_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, inputs_dict def lowerCamelCase_ ( self: int , UpperCamelCase__: Dict , UpperCamelCase__: Dict ): lowerCamelCase__ : Dict = TFMBartModel(config=__lowerCamelCase ).get_decoder() lowerCamelCase__ : Any = inputs_dict["input_ids"] lowerCamelCase__ : Optional[int] = input_ids[:1, :] lowerCamelCase__ : Any = inputs_dict["attention_mask"][:1, :] lowerCamelCase__ : List[str] = inputs_dict["head_mask"] lowerCamelCase__ : Dict = 1 # first forward pass lowerCamelCase__ : str = model(__lowerCamelCase , attention_mask=__lowerCamelCase , head_mask=__lowerCamelCase , use_cache=__lowerCamelCase ) lowerCamelCase__ : Any = outputs.to_tuple() lowerCamelCase__ : Optional[int] = past_key_values[1] def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , ) -> int: if attention_mask is None: lowerCamelCase__ : List[str] = tf.cast(tf.math.not_equal(_A , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCamelCase__ : Optional[int] = 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: lowerCamelCase__ : int = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCamelCase__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCamelCase__ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowercase ( lowercase__ , lowercase__ , unittest.TestCase ): a = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () a = (TFMBartForConditionalGeneration,) if is_tf_available() else () a = ( { """conversational""": TFMBartForConditionalGeneration, """feature-extraction""": TFMBartModel, """summarization""": TFMBartForConditionalGeneration, """text2text-generation""": TFMBartForConditionalGeneration, """translation""": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) a = True a = False a = False def lowerCamelCase_ ( self: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple ): if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : List[str] = TFMBartModelTester(self ) lowerCamelCase__ : str = ConfigTester(self , config_class=__lowerCamelCase ) def lowerCamelCase_ ( self: List[str] ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class _lowercase ( unittest.TestCase ): a = [ """ UN Chief Says There Is No Military Solution in Syria""", ] a = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", ] a = """facebook/mbart-large-en-ro""" @cached_property def lowerCamelCase_ ( self: Optional[int] ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def lowerCamelCase_ ( self: Any , **UpperCamelCase__: Tuple ): lowerCamelCase__ : Tuple = self.translate_src_text(**__lowerCamelCase ) self.assertListEqual(self.expected_text , __lowerCamelCase ) def lowerCamelCase_ ( self: Optional[int] , **UpperCamelCase__: List[str] ): lowerCamelCase__ : Optional[Any] = self.tokenizer(self.src_text , **__lowerCamelCase , return_tensors="""tf""" ) lowerCamelCase__ : Tuple = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) lowerCamelCase__ : List[Any] = self.tokenizer.batch_decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) return generated_words @slow def lowerCamelCase_ ( self: Optional[int] ): self._assert_generated_batch_equal_expected()
705
'''simple docstring''' from statistics import mean import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : Optional[int] = 0 # Number of processes finished lowerCamelCase__ : Union[str, Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowerCamelCase__ : Tuple = [0] * no_of_process # List to include calculation results lowerCamelCase__ : List[str] = [0] * no_of_process # Sort by arrival time. lowerCamelCase__ : Union[str, Any] = [burst_time[i] for i in np.argsort(UpperCamelCase )] lowerCamelCase__ : List[Any] = [process_name[i] for i in np.argsort(UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: lowerCamelCase__ : str = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowerCamelCase__ : Union[str, Any] = arrival_time[i] lowerCamelCase__ : Any = 0 # Index showing the location of the process being performed lowerCamelCase__ : Union[str, Any] = 0 # Saves the current response ratio. lowerCamelCase__ : Any = 0 for i in range(0 , UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowerCamelCase__ : Optional[int] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowerCamelCase__ : int = temp lowerCamelCase__ : str = i # Calculate the turn around time lowerCamelCase__ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowerCamelCase__ : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : int = [0] * no_of_process for i in range(0 , UpperCamelCase ): lowerCamelCase__ : Optional[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _A : List[str] =5 _A : Optional[Any] =['''A''', '''B''', '''C''', '''D''', '''E'''] _A : Optional[int] =[1, 2, 3, 4, 5] _A : Dict =[1, 2, 3, 4, 5] _A : Any =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _A : Optional[int] =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
631
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> set: lowerCamelCase__ : List[str] = set() # edges = list of graph's edges lowerCamelCase__ : Optional[int] = get_edges(lowerCamelCase_ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: lowerCamelCase__ : List[str] = edges.pop() chosen_vertices.add(lowerCamelCase_ ) chosen_vertices.add(lowerCamelCase_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowerCamelCase_ ) return chosen_vertices def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> set: lowerCamelCase__ : Optional[int] = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
706
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
631
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _A : Tuple ={ "configuration_convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig", "ConvNextOnnxConfig"] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Dict =["ConvNextFeatureExtractor"] _A : Dict =["ConvNextImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Dict =[ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : List[str] =[ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys _A : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
707
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowercase : def __init__( self: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Optional[int]=30 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: List[str]=3 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=True , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Any=5 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Dict=37 , UpperCamelCase__: List[Any]="gelu" , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: List[Any]=10 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Optional[int]=3 , UpperCamelCase__: Dict=0.6 , UpperCamelCase__: int=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Optional[Any] = patch_size lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Any = is_training lowerCamelCase__ : Union[str, Any] = use_labels lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Any = hidden_dropout_prob lowerCamelCase__ : Optional[int] = attention_probs_dropout_prob lowerCamelCase__ : List[Any] = type_sequence_label_size lowerCamelCase__ : int = initializer_range lowerCamelCase__ : List[str] = mask_ratio lowerCamelCase__ : List[Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowerCamelCase__ : str = (image_size // patch_size) ** 2 lowerCamelCase__ : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: str ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int ): lowerCamelCase__ : Tuple = ViTMAEModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : List[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): lowerCamelCase__ : int = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Any = (self.image_size // self.patch_size) ** 2 lowerCamelCase__ : str = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowerCamelCase__ : Dict = 1 lowerCamelCase__ : Optional[int] = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = config_and_inputs lowerCamelCase__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () a = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} a = False a = False a = False a = False def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Tuple = ViTMAEModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase_ ( self: Dict ): pass def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Any = model_class(UpperCamelCase__ ) lowerCamelCase__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Any = [*signature.parameters.keys()] lowerCamelCase__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] ): # make masks reproducible np.random.seed(2 ) lowerCamelCase__ : Tuple = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) lowerCamelCase__ : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCamelCase__ : Tuple = torch.from_numpy(UpperCamelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowerCamelCase__ : Tuple = pt_noise super().check_pt_tf_models(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Optional[int] = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs[0].cpu().numpy() lowerCamelCase__ : List[str] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model_class.from_pretrained(UpperCamelCase__ ) model.to(UpperCamelCase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) # Make sure we don't have nans lowerCamelCase__ : Dict = after_outputs[0].cpu().numpy() lowerCamelCase__ : Tuple = 0 lowerCamelCase__ : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase__ , 1e-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: Any ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase_ ( self: Tuple ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Optional[int] ): pass @slow def lowerCamelCase_ ( self: List[str] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Tuple = ViTMAEModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> List[Any]: lowerCamelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: List[str] ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self: Tuple ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) lowerCamelCase__ : str = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : int = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowerCamelCase__ : List[str] = ViTMAEConfig() lowerCamelCase__ : int = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowerCamelCase__ : Any = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ , noise=torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ ) ) # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : str = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCamelCase__ ) , atol=1e-4 ) )
631
0
'''simple docstring''' class _lowercase : def __init__( self: Dict , UpperCamelCase__: Any ): lowerCamelCase__ : str = val lowerCamelCase__ : Tuple = None lowerCamelCase__ : List[str] = None def lowerCamelCase_ ( self: Any , UpperCamelCase__: str ): if self.val: if val < self.val: if self.left is None: lowerCamelCase__ : str = Node(UpperCamelCase__ ) else: self.left.insert(UpperCamelCase__ ) elif val > self.val: if self.right is None: lowerCamelCase__ : List[Any] = Node(UpperCamelCase__ ) else: self.right.insert(UpperCamelCase__ ) else: lowerCamelCase__ : Tuple = val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Tuple: if root: inorder(root.left , __A ) res.append(root.val ) inorder(root.right , __A ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: if len(__A ) == 0: return arr lowerCamelCase__ : List[str] = Node(arr[0] ) for i in range(1 , len(__A ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCamelCase__ : int = [] inorder(__A , __A ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
708
'''simple docstring''' import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _lowercase ( _lowercase ): a = """""" a = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a = None # compression type in fsspec. ex: "gzip" a = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self: str , UpperCamelCase__: str = "" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , **UpperCamelCase__: List[Any] ): super().__init__(self , **UpperCamelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode lowerCamelCase__ : List[Any] = fsspec.open( UpperCamelCase__ , mode="""rb""" , protocol=UpperCamelCase__ , compression=self.compression , client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) lowerCamelCase__ : str = os.path.basename(self.file.path.split("""::""" )[0] ) lowerCamelCase__ : Union[str, Any] = ( self.compressed_name[: self.compressed_name.rindex(""".""" )] if """.""" in self.compressed_name else self.compressed_name ) lowerCamelCase__ : Tuple = None @classmethod def lowerCamelCase_ ( cls: Optional[int] , UpperCamelCase__: Optional[int] ): # compressed file paths are always relative to the archive root return super()._strip_protocol(UpperCamelCase__ ).lstrip("""/""" ) def lowerCamelCase_ ( self: Tuple ): if self.dir_cache is None: lowerCamelCase__ : Dict = {**self.file.fs.info(self.file.path ), """name""": self.uncompressed_name} lowerCamelCase__ : int = {f["""name"""]: f} def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: str ): return self.file.open().read() def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[int]=None , UpperCamelCase__: Tuple=True , UpperCamelCase__: Tuple=None , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Union[str, Any] = self._strip_protocol(UpperCamelCase__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class _lowercase ( _lowercase ): a = """bz2""" a = """bz2""" a = """.bz2""" class _lowercase ( _lowercase ): a = """gzip""" a = """gzip""" a = """.gz""" class _lowercase ( _lowercase ): a = """lz4""" a = """lz4""" a = """.lz4""" class _lowercase ( _lowercase ): a = """xz""" a = """xz""" a = """.xz""" class _lowercase ( _lowercase ): a = """zstd""" a = """zstd""" a = """.zst""" def __init__( self: int , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , UpperCamelCase__: int = DEFAULT_BLOCK_SIZE , **UpperCamelCase__: Dict , ): super().__init__( fo=UpperCamelCase__ , mode=UpperCamelCase__ , target_protocol=UpperCamelCase__ , target_options=UpperCamelCase__ , block_size=UpperCamelCase__ , **UpperCamelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 lowerCamelCase__ : Tuple = self.file.__enter__ class _lowercase : def __init__( self: Optional[int] , UpperCamelCase__: Any ): lowerCamelCase__ : Optional[int] = file_ def __enter__( self: List[Any] ): self._file.__enter__() return self def __exit__( self: Any , *UpperCamelCase__: str , **UpperCamelCase__: Any ): self._file.__exit__(*UpperCamelCase__ , **UpperCamelCase__ ) def __iter__( self: Any ): return iter(self._file ) def lowerCamelCase_ ( self: List[Any] ): return next(self._file ) def __getattr__( self: List[str] , UpperCamelCase__: Dict ): return getattr(self._file , UpperCamelCase__ ) def fixed_enter(*UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[str] ): return WrappedFile(_enter(*UpperCamelCase__ , **UpperCamelCase__ ) ) lowerCamelCase__ : Optional[Any] = fixed_enter
631
0
'''simple docstring''' from math import factorial _A : dict[str, int] ={str(digit): factorial(digit) for digit in range(10)} def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Tuple: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError("""Parameter number must be int""" ) if number < 0: raise ValueError("""Parameter number must be greater than or equal to 0""" ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 60 , UpperCamelCase = 1000000 ) -> Optional[Any]: if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError("""Parameters chain_length and number_limit must be int""" ) if chain_length <= 0 or number_limit <= 0: raise ValueError( """Parameters chain_length and number_limit must be greater than 0""" ) # the counter for the chains with the exact desired length lowerCamelCase__ : int = 0 # the cached sizes of the previous chains lowerCamelCase__ : Union[str, Any] = {} for start_chain_element in range(1 , __lowerCAmelCase ): # The temporary set will contain the elements of the chain lowerCamelCase__ : int = set() lowerCamelCase__ : Union[str, Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. lowerCamelCase__ : Any = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(__lowerCAmelCase ) chain_set_length += 1 lowerCamelCase__ : str = digit_factorial_sum(__lowerCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] lowerCamelCase__ : List[str] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'{solution()}')
709
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() _A : int =logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: print("""Loading config file...""" ) def flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase="" , UpperCamelCase="." ): lowerCamelCase__ : Optional[int] = [] for k, v in d.items(): lowerCamelCase__ : Optional[int] = parent_key + sep + k if parent_key else k if isinstance(UpperCamelCase , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase , sep=UpperCamelCase ).items() ) else: items.append((new_key, v) ) return dict(UpperCamelCase ) lowerCamelCase__ : Any = argparse.Namespace() with open(UpperCamelCase , """r""" ) as yaml_file: try: lowerCamelCase__ : int = yaml.load(UpperCamelCase , Loader=yaml.FullLoader ) lowerCamelCase__ : Tuple = flatten_yaml_as_dict(UpperCamelCase ) for k, v in flat_cfg.items(): setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) except yaml.YAMLError as exc: logger.error("""Error while loading config file: {}. Error message: {}""".format(UpperCamelCase , str(UpperCamelCase ) ) ) return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Union[str, Any] = MobileViTVaConfig() lowerCamelCase__ : str = False # dataset if task_name.startswith("""imagenet1k_""" ): lowerCamelCase__ : Optional[Any] = 1000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : int = 384 else: lowerCamelCase__ : Optional[int] = 256 lowerCamelCase__ : str = """imagenet-1k-id2label.json""" elif task_name.startswith("""imagenet21k_to_1k_""" ): lowerCamelCase__ : Tuple = 21000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : str = 384 else: lowerCamelCase__ : Any = 256 lowerCamelCase__ : int = """imagenet-22k-id2label.json""" elif task_name.startswith("""ade20k_""" ): lowerCamelCase__ : Dict = 151 lowerCamelCase__ : str = 512 lowerCamelCase__ : List[Any] = """ade20k-id2label.json""" lowerCamelCase__ : Union[str, Any] = True elif task_name.startswith("""voc_""" ): lowerCamelCase__ : Tuple = 21 lowerCamelCase__ : Optional[int] = 512 lowerCamelCase__ : List[Any] = """pascal-voc-id2label.json""" lowerCamelCase__ : Tuple = True # orig_config lowerCamelCase__ : Optional[int] = load_orig_config_file(UpperCamelCase ) assert getattr(UpperCamelCase , """model.classification.name""" , -1 ) == "mobilevit_v2", "Invalid model" lowerCamelCase__ : int = getattr(UpperCamelCase , """model.classification.mitv2.width_multiplier""" , 1.0 ) assert ( getattr(UpperCamelCase , """model.classification.mitv2.attn_norm_layer""" , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.classification.activation.name""" , """swish""" ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: lowerCamelCase__ : Any = getattr(UpperCamelCase , """model.segmentation.output_stride""" , 16 ) if "_deeplabv3" in task_name: lowerCamelCase__ : str = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_rates""" , [12, 24, 36] ) lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_out_channels""" , 512 ) lowerCamelCase__ : List[Any] = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_dropout""" , 0.1 ) # id2label lowerCamelCase__ : Tuple = """huggingface/label-files""" lowerCamelCase__ : Optional[Any] = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase__ : Union[str, Any] = {int(UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : int = idalabel lowerCamelCase__ : Optional[Any] = {v: k for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any: lowerCamelCase__ : List[Any] = dct.pop(UpperCamelCase ) lowerCamelCase__ : Dict = val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> Tuple: if base_model: lowerCamelCase__ : Optional[int] = """""" else: lowerCamelCase__ : Optional[Any] = """mobilevitv2.""" lowerCamelCase__ : List[str] = [] for k in state_dict.keys(): if k[:8] == "encoder.": lowerCamelCase__ : Optional[Any] = k[8:] else: lowerCamelCase__ : Optional[Any] = k if ".block." in k: lowerCamelCase__ : Dict = k_new.replace(""".block.""" , """.""" ) if ".conv." in k: lowerCamelCase__ : List[Any] = k_new.replace(""".conv.""" , """.convolution.""" ) if ".norm." in k: lowerCamelCase__ : str = k_new.replace(""".norm.""" , """.normalization.""" ) if "conv_1." in k: lowerCamelCase__ : Any = k_new.replace("""conv_1.""" , f'''{model_prefix}conv_stem.''' ) for i in [1, 2]: if f'''layer_{i}.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.''' , f'''{model_prefix}encoder.layer.{i-1}.layer.''' ) if ".exp_1x1." in k: lowerCamelCase__ : Dict = k_new.replace(""".exp_1x1.""" , """.expand_1x1.""" ) if ".red_1x1." in k: lowerCamelCase__ : str = k_new.replace(""".red_1x1.""" , """.reduce_1x1.""" ) for i in [3, 4, 5]: if f'''layer_{i}.0.''' in k: lowerCamelCase__ : List[str] = k_new.replace(f'''layer_{i}.0.''' , f'''{model_prefix}encoder.layer.{i-1}.downsampling_layer.''' ) if f'''layer_{i}.1.local_rep.0.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.1.local_rep.0.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_kxk.''' ) if f'''layer_{i}.1.local_rep.1.''' in k: lowerCamelCase__ : Dict = k_new.replace(f'''layer_{i}.1.local_rep.1.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_1x1.''' ) for i in [3, 4, 5]: if i == 3: lowerCamelCase__ : int = [0, 1] elif i == 4: lowerCamelCase__ : str = [0, 1, 2, 3] elif i == 5: lowerCamelCase__ : Dict = [0, 1, 2] for j in j_in: if f'''layer_{i}.1.global_rep.{j}.''' in k: lowerCamelCase__ : List[Any] = k_new.replace( f'''layer_{i}.1.global_rep.{j}.''' , f'''{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.''' ) if f'''layer_{i}.1.global_rep.{j+1}.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace( f'''layer_{i}.1.global_rep.{j+1}.''' , f'''{model_prefix}encoder.layer.{i-1}.layernorm.''' ) if f'''layer_{i}.1.conv_proj.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace(f'''layer_{i}.1.conv_proj.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_projection.''' ) if "pre_norm_attn.0." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.0.""" , """layernorm_before.""" ) if "pre_norm_attn.1." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.1.""" , """attention.""" ) if "pre_norm_ffn.0." in k: lowerCamelCase__ : Optional[Any] = k_new.replace("""pre_norm_ffn.0.""" , """layernorm_after.""" ) if "pre_norm_ffn.1." in k: lowerCamelCase__ : Union[str, Any] = k_new.replace("""pre_norm_ffn.1.""" , """ffn.conv1.""" ) if "pre_norm_ffn.3." in k: lowerCamelCase__ : List[Any] = k_new.replace("""pre_norm_ffn.3.""" , """ffn.conv2.""" ) if "classifier.1." in k: lowerCamelCase__ : Tuple = k_new.replace("""classifier.1.""" , """classifier.""" ) if "seg_head." in k: lowerCamelCase__ : Optional[int] = k_new.replace("""seg_head.""" , """segmentation_head.""" ) if ".aspp_layer." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_pool.""" , """.""" ) rename_keys.append((k, k_new) ) return rename_keys def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: lowerCamelCase__ : Union[str, Any] = [] for k in state_dict.keys(): if k.startswith("""seg_head.aux_head.""" ): keys_to_ignore.append(UpperCamelCase ) for k in keys_to_ignore: state_dict.pop(UpperCamelCase , UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Dict: lowerCamelCase__ : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" lowerCamelCase__ : Tuple = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCamelCase__ : str = get_mobilevitva_config(UpperCamelCase , UpperCamelCase ) # load original state_dict lowerCamelCase__ : List[str] = torch.load(UpperCamelCase , map_location="""cpu""" ) # load huggingface model if task_name.startswith("""ade20k_""" ) or task_name.startswith("""voc_""" ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation(UpperCamelCase ).eval() lowerCamelCase__ : Tuple = False else: lowerCamelCase__ : int = MobileViTVaForImageClassification(UpperCamelCase ).eval() lowerCamelCase__ : Optional[Any] = False # remove and rename some keys of load the original model lowerCamelCase__ : Tuple = checkpoint remove_unused_keys(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = create_rename_keys(UpperCamelCase , base_model=UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # load modified state_dict model.load_state_dict(UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor lowerCamelCase__ : int = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) lowerCamelCase__ : Dict = image_processor(images=prepare_img() , return_tensors="""pt""" ) lowerCamelCase__ : str = model(**UpperCamelCase ) # verify classification model if task_name.startswith("""imagenet""" ): lowerCamelCase__ : Dict = outputs.logits lowerCamelCase__ : Optional[Any] = logits.argmax(-1 ).item() print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] ) if task_name.startswith("""imagenet1k_256""" ) and config.width_multiplier == 1.0: # expected_logits for base variant lowerCamelCase__ : Optional[Any] = torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01] ) assert torch.allclose(logits[0, :3] , UpperCamelCase , atol=1E-4 ) Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(f'''Saving model {task_name} 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 __name__ == "__main__": _A : Optional[int] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''imagenet1k_256''', type=str, help=( '''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ''' ''' Classification (ImageNet-1k) - MobileViTV2 (256x256) : imagenet1k_256 - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384 - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) : imagenet21k_to_1k_256 - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on ImageNet-1k 384x384) : imagenet21k_to_1k_384 Segmentation - ADE20K Dataset : ade20k_deeplabv3 - Pascal VOC 2012 Dataset: voc_deeplabv3 ''' ), choices=[ '''imagenet1k_256''', '''imagenet1k_384''', '''imagenet21k_to_1k_256''', '''imagenet21k_to_1k_384''', '''ade20k_deeplabv3''', '''voc_deeplabv3''', ], ) parser.add_argument( '''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) _A : Dict =parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
631
0
'''simple docstring''' from __future__ import annotations import math def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True _A : Optional[int] =[num for num in range(3, 100_001, 2) if not is_prime(num)] def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> list[int]: if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise ValueError("""n must be an integer""" ) if n <= 0: raise ValueError("""n must be >= 0""" ) lowerCamelCase__ : int = [] for num in range(len(lowerCamelCase__ ) ): lowerCamelCase__ : List[Any] = 0 while 2 * i * i <= odd_composites[num]: lowerCamelCase__ : Tuple = odd_composites[num] - 2 * i * i if is_prime(lowerCamelCase__ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowerCamelCase__ ) == n: return list_nums return [] def SCREAMING_SNAKE_CASE_ () -> int: return compute_nums(1 )[0] if __name__ == "__main__": print(F'{solution() = }')
710
'''simple docstring''' import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _lowercase ( _lowercase ): def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCamelCase__ , """width_multiplier""" ) ) class _lowercase : def __init__( self: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: str=13 , UpperCamelCase__: Any=64 , UpperCamelCase__: Optional[Any]=2 , UpperCamelCase__: str=3 , UpperCamelCase__: List[str]="swish" , UpperCamelCase__: Any=3 , UpperCamelCase__: Optional[int]=32 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: int=0.02 , UpperCamelCase__: Dict=True , UpperCamelCase__: Dict=True , UpperCamelCase__: Any=10 , UpperCamelCase__: int=None , UpperCamelCase__: List[Any]=0.25 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Optional[int]=0.0 , ): lowerCamelCase__ : Any = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : str = patch_size lowerCamelCase__ : Optional[int] = num_channels lowerCamelCase__ : Optional[Any] = make_divisible(512 * width_multiplier , divisor=8 ) lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : Any = conv_kernel_size lowerCamelCase__ : Any = output_stride lowerCamelCase__ : Union[str, Any] = classifier_dropout_prob lowerCamelCase__ : List[str] = use_labels lowerCamelCase__ : Optional[Any] = is_training lowerCamelCase__ : List[str] = num_labels lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[Any] = scope lowerCamelCase__ : Tuple = width_multiplier lowerCamelCase__ : List[Any] = ffn_dropout lowerCamelCase__ : Any = attn_dropout def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Tuple = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase__ : str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCamelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCamelCase_ ( self: List[Any] ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Union[str, Any] = MobileViTVaModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : str = model(UpperCamelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : Tuple = self.num_labels lowerCamelCase__ : Dict = MobileViTVaForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str ): lowerCamelCase__ : List[str] = self.num_labels lowerCamelCase__ : Union[str, Any] = MobileViTVaForSemanticSegmentation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase__ : List[Any] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Any = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) a = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) a = False a = False a = False a = False def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = MobileViTVaModelTester(self ) lowerCamelCase__ : List[str] = MobileViTVaConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def lowerCamelCase_ ( self: Union[str, Any] ): pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Tuple ): pass def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ , lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Tuple = [*signature.parameters.keys()] lowerCamelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): def check_hidden_states_output(UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs.hidden_states lowerCamelCase__ : List[Any] = 5 self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase__ : int = 2 for i in range(len(UpperCamelCase__ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCamelCase__ , lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : int = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__ : str = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Union[str, Any] = MobileViTVaModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> Optional[int]: lowerCamelCase__ : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: Tuple ): return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[Any] = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = self.default_image_processor lowerCamelCase__ : List[Any] = prepare_img() lowerCamelCase__ : Any = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : int = model(**UpperCamelCase__ ) # verify the logits lowerCamelCase__ : str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Any = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Union[str, Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Optional[Any] = model(**UpperCamelCase__ ) lowerCamelCase__ : str = outputs.logits # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Any = torch.tensor( [ [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]], [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]], [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]], ] , device=UpperCamelCase__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Optional[Any] = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : List[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Dict = model(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = outputs.logits.detach().cpu() lowerCamelCase__ : List[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ , target_sizes=[(50, 60)] ) lowerCamelCase__ : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ ) lowerCamelCase__ : int = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ )
631
0
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , ) -> Dict: if config_name_or_path is None: lowerCamelCase__ : Any = "facebook/rag-token-base" if model_type == "rag_token" else "facebook/rag-sequence-base" if generator_tokenizer_name_or_path is None: lowerCamelCase__ : Tuple = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: lowerCamelCase__ : List[str] = question_encoder_name_or_path lowerCamelCase__ : Optional[Any] = RagTokenForGeneration if model_type == "rag_token" else RagSequenceForGeneration # Save model. lowerCamelCase__ : Union[str, Any] = RagConfig.from_pretrained(_lowerCAmelCase ) lowerCamelCase__ : List[Any] = AutoConfig.from_pretrained(_lowerCAmelCase ) lowerCamelCase__ : Optional[Any] = AutoConfig.from_pretrained(_lowerCAmelCase ) lowerCamelCase__ : Tuple = gen_config lowerCamelCase__ : Any = question_encoder_config lowerCamelCase__ : List[Any] = model_class.from_pretrained_question_encoder_generator( _lowerCAmelCase , _lowerCAmelCase , config=_lowerCAmelCase ) rag_model.save_pretrained(_lowerCAmelCase ) # Sanity check. model_class.from_pretrained(_lowerCAmelCase ) # Save tokenizers. lowerCamelCase__ : str = AutoTokenizer.from_pretrained(_lowerCAmelCase ) gen_tokenizer.save_pretrained(dest_dir / """generator_tokenizer/""" ) lowerCamelCase__ : List[Any] = AutoTokenizer.from_pretrained(_lowerCAmelCase ) question_encoder_tokenizer.save_pretrained(dest_dir / """question_encoder_tokenizer/""" ) if __name__ == "__main__": _A : int =argparse.ArgumentParser() parser.add_argument( '''--model_type''', choices=['''rag_sequence''', '''rag_token'''], required=True, type=str, help='''RAG model type: rag_sequence, rag_token''', ) parser.add_argument('''--dest''', type=str, required=True, help='''Path to the output checkpoint directory.''') parser.add_argument('''--generator_name_or_path''', type=str, required=True, help='''Generator model identifier''') parser.add_argument( '''--question_encoder_name_or_path''', type=str, required=True, help='''Question encoder model identifier''' ) parser.add_argument( '''--generator_tokenizer_name_or_path''', type=str, help='''Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``''', ) parser.add_argument( '''--question_encoder_tokenizer_name_or_path''', type=str, help='''Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``''', ) parser.add_argument( '''--config_name_or_path''', type=str, help=( '''Identifier of the model config to use, if not provided, resolves to a base config for a given''' ''' ``model_type``''' ), ) _A : Tuple =parser.parse_args() _A : int =Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
711
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _A : Optional[Any] =logging.get_logger(__name__) _A : Dict ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _A : Tuple ={ '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } _A : List[Any] ={ '''gpt-neox-20b''': 2_048, } class _lowercase ( _lowercase ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["""input_ids""", """attention_mask"""] def __init__( self: Optional[int] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: int=None , UpperCamelCase__: Tuple=None , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Union[str, Any]="<|endoftext|>" , UpperCamelCase__: Tuple=False , **UpperCamelCase__: str , ): super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , **UpperCamelCase__ , ) lowerCamelCase__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: lowerCamelCase__ : Any = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) ) lowerCamelCase__ : Dict = add_prefix_space lowerCamelCase__ : Optional[int] = pre_tok_class(**UpperCamelCase__ ) lowerCamelCase__ : Dict = add_prefix_space def lowerCamelCase_ ( self: int , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): lowerCamelCase__ : Optional[Any] = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: "Conversation" ): lowerCamelCase__ : str = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [self.eos_token_id] ) if len(UpperCamelCase__ ) > self.model_max_length: lowerCamelCase__ : int = input_ids[-self.model_max_length :] return input_ids
631
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _A : Optional[int] =logging.get_logger(__name__) _A : Optional[int] ={"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _A : Optional[int] ={ "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } _A : Dict ={ "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } _A : Dict ={ "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _lowercase ( UpperCamelCase_ ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = PRETRAINED_INIT_CONFIGURATION a = ["""input_ids""", """attention_mask"""] a = DistilBertTokenizer def __init__( self: Optional[int] , UpperCamelCase__: List[str]=None , UpperCamelCase__: Optional[Any]=None , UpperCamelCase__: Any=True , UpperCamelCase__: Any="[UNK]" , UpperCamelCase__: Tuple="[SEP]" , UpperCamelCase__: Union[str, Any]="[PAD]" , UpperCamelCase__: Optional[int]="[CLS]" , UpperCamelCase__: Optional[int]="[MASK]" , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: Union[str, Any]=None , **UpperCamelCase__: int , ): super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , tokenize_chinese_chars=_a , strip_accents=_a , **_a , ) lowerCamelCase__ : Union[str, Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , _a ) != do_lower_case or normalizer_state.get("""strip_accents""" , _a ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , _a ) != tokenize_chinese_chars ): lowerCamelCase__ : int = getattr(_a , normalizer_state.pop("""type""" ) ) lowerCamelCase__ : Union[str, Any] = do_lower_case lowerCamelCase__ : Optional[Any] = strip_accents lowerCamelCase__ : Optional[Any] = tokenize_chinese_chars lowerCamelCase__ : Union[str, Any] = normalizer_class(**_a ) lowerCamelCase__ : List[Any] = do_lower_case def lowerCamelCase_ ( self: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: Any=None ): lowerCamelCase__ : Optional[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str] = None ): lowerCamelCase__ : List[str] = [self.sep_token_id] lowerCamelCase__ : 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 ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase_ ( self: str , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict = None ): lowerCamelCase__ : str = self._tokenizer.model.save(_a , name=_a ) return tuple(_a )
712
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A : Dict ={ '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
0
'''simple docstring''' import numpy # List of input, output pairs _A : Tuple =( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) _A : Dict =(((515, 22, 13), 555), ((61, 35, 49), 150)) _A : List[str] =[2, 4, 1, 5] _A : Dict =len(train_data) _A : str =0.009 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase="train" ) -> Union[str, Any]: return calculate_hypothesis_value(__UpperCAmelCase , __UpperCAmelCase ) - output( __UpperCAmelCase , __UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = 0 for i in range(len(__UpperCAmelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[int]: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> str: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=m ) -> Optional[int]: lowerCamelCase__ : int = 0 for i in range(__UpperCAmelCase ): if index == -1: summation_value += _error(__UpperCAmelCase ) else: summation_value += _error(__UpperCAmelCase ) * train_data[i][0][index] return summation_value def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Union[str, Any]: lowerCamelCase__ : Union[str, Any] = summation_of_cost_derivative(__UpperCAmelCase , __UpperCAmelCase ) / m return cost_derivative_value def SCREAMING_SNAKE_CASE_ () -> Any: global parameter_vector # Tune these values to set a tolerance value for predicted output lowerCamelCase__ : Tuple = 0.00_0002 lowerCamelCase__ : str = 0 lowerCamelCase__ : Tuple = 0 while True: j += 1 lowerCamelCase__ : Tuple = [0, 0, 0, 0] for i in range(0 , len(__UpperCAmelCase ) ): lowerCamelCase__ : Any = get_cost_derivative(i - 1 ) lowerCamelCase__ : Union[str, Any] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( __UpperCAmelCase , __UpperCAmelCase , atol=__UpperCAmelCase , rtol=__UpperCAmelCase , ): break lowerCamelCase__ : Dict = temp_parameter_vector print(("""Number of iterations:""", j) ) def SCREAMING_SNAKE_CASE_ () -> str: for i in range(len(__UpperCAmelCase ) ): print(("""Actual output value:""", output(__UpperCAmelCase , """test""" )) ) print(("""Hypothesis output:""", calculate_hypothesis_value(__UpperCAmelCase , """test""" )) ) if __name__ == "__main__": run_gradient_descent() print('''\nTesting gradient descent for a linear hypothesis function.\n''') test_gradient_descent()
713
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin _A : int =get_tests_dir('''fixtures/test_sentencepiece.model''') _A : Tuple ={'''target_lang''': '''fi''', '''source_lang''': '''en'''} _A : int ='''>>zh<<''' _A : Dict ='''Helsinki-NLP/''' if is_torch_available(): _A : List[Any] ='''pt''' elif is_tf_available(): _A : Optional[int] ='''tf''' else: _A : Dict ='''jax''' @require_sentencepiece class _lowercase ( _lowercase , unittest.TestCase ): a = MarianTokenizer a = False a = True def lowerCamelCase_ ( self: List[str] ): super().setUp() lowerCamelCase__ : List[Any] = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] lowerCamelCase__ : Optional[Any] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) lowerCamelCase__ : Optional[int] = Path(self.tmpdirname ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) lowerCamelCase__ : Dict = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self: Optional[Any] , **UpperCamelCase__: Any ): return MarianTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] ): return ( "This is a test", "This is a test", ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Any = """</s>""" lowerCamelCase__ : List[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__ ) , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(UpperCamelCase__ ) , 9 ) def lowerCamelCase_ ( self: int ): self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def lowerCamelCase_ ( self: int ): lowerCamelCase__ : List[Any] = MarianTokenizer.from_pretrained(F'''{ORG_NAME}opus-mt-en-de''' ) lowerCamelCase__ : Optional[int] = en_de_tokenizer(["""I am a small frog"""] , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [38, 121, 14, 697, 38_848, 0] self.assertListEqual(UpperCamelCase__ , batch.input_ids[0] ) lowerCamelCase__ : List[str] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : Tuple = [x.name for x in Path(UpperCamelCase__ ).glob("""*""" )] self.assertIn("""source.spm""" , UpperCamelCase__ ) MarianTokenizer.from_pretrained(UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : List[Any] = self.get_tokenizer() lowerCamelCase__ : Any = tok( ["""I am a small frog""" * 1_000, """I am a small frog"""] , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Dict = tok(["""I am a tiny frog""", """I am a small frog"""] , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def lowerCamelCase_ ( self: List[str] ): # fmt: off lowerCamelCase__ : int = {"""input_ids""": [[43_495, 462, 20, 42_164, 1_369, 52, 464, 132, 1_703, 492, 13, 7_491, 38_999, 6, 8, 464, 132, 1_703, 492, 13, 4_669, 37_867, 13, 7_525, 27, 1_593, 988, 13, 33_972, 7_029, 6, 20, 8_251, 383, 2, 270, 5_866, 3_788, 2, 2_353, 8_251, 12_338, 2, 13_958, 387, 2, 3_629, 6_953, 188, 2_900, 2, 13_958, 8_011, 11_501, 23, 8_460, 4_073, 34_009, 20, 435, 11_439, 27, 8, 8_460, 4_073, 6_004, 20, 9_988, 375, 27, 33, 266, 1_945, 1_076, 1_350, 37_867, 3_288, 5, 577, 1_076, 4_374, 8, 5_082, 5, 26_453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10_767, 6, 316, 304, 4_239, 3, 0], [148, 15_722, 19, 1_839, 12, 1_350, 13, 22_327, 5_082, 5_418, 47_567, 35_938, 59, 318, 19_552, 108, 2_183, 54, 14_976, 4_835, 32, 547, 1_114, 8, 315, 2_417, 5, 92, 19_088, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100], [36, 6_395, 12_570, 39_147, 11_597, 6, 266, 4, 45_405, 7_296, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase__ , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Union[str, Any] = MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) lowerCamelCase__ : str = """Tämä on testi""" lowerCamelCase__ : Any = """This is a test""" lowerCamelCase__ : int = [76, 7, 2_047, 2] lowerCamelCase__ : List[str] = [69, 12, 11, 940, 2] lowerCamelCase__ : Tuple = tokenizer(UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = tokenizer(text_target=UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Tuple = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
631
0
'''simple docstring''' import requests from bsa import BeautifulSoup def SCREAMING_SNAKE_CASE_ (UpperCamelCase = "https://www.worldometers.info/coronavirus" ) -> str: lowerCamelCase__ : List[str] = BeautifulSoup(requests.get(lowerCAmelCase__ ).text , """html.parser""" ) lowerCamelCase__ : Optional[int] = soup.findAll("""h1""" ) lowerCamelCase__ : Tuple = soup.findAll("""div""" , {"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" , {"""class""": """panel-title"""} ) values += soup.findAll("""div""" , {"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(lowerCAmelCase__ , lowerCAmelCase__ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F'{key}\n{value}\n')
714
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Optional[Any] =logging.get_logger(__name__) _A : Optional[int] ={ '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """rwkv""" a = {"""max_position_embeddings""": """context_length"""} def __init__( self: Tuple , UpperCamelCase__: Optional[Any]=50_277 , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Tuple=4_096 , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Dict=None , UpperCamelCase__: Dict=None , UpperCamelCase__: int=1e-5 , UpperCamelCase__: Any=0 , UpperCamelCase__: str=0 , UpperCamelCase__: Union[str, Any]=6 , UpperCamelCase__: Optional[int]=False , UpperCamelCase__: Dict=True , **UpperCamelCase__: Dict , ): lowerCamelCase__ : Dict = vocab_size lowerCamelCase__ : Optional[Any] = context_length lowerCamelCase__ : Optional[Any] = hidden_size lowerCamelCase__ : Any = num_hidden_layers lowerCamelCase__ : int = attention_hidden_size if attention_hidden_size is not None else hidden_size lowerCamelCase__ : Union[str, Any] = intermediate_size if intermediate_size is not None else 4 * hidden_size lowerCamelCase__ : List[str] = layer_norm_epsilon lowerCamelCase__ : int = rescale_every lowerCamelCase__ : Optional[int] = use_cache lowerCamelCase__ : Dict = bos_token_id lowerCamelCase__ : Any = eos_token_id super().__init__( tie_word_embeddings=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
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. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _lowercase ( __lowerCAmelCase ): a = """naver-clova-ix/donut-base-finetuned-docvqa""" a = ( """This is a tool that answers a question about an document (pdf). It takes an input named `document` which """ """should be the document containing the information, as well as a `question` that is the question about the """ """document. It returns a text that contains the answer to the question.""" ) a = """document_qa""" a = AutoProcessor a = VisionEncoderDecoderModel a = ["""image""", """text"""] a = ["""text"""] def __init__( self: Union[str, Any] , *UpperCamelCase__: Optional[Any] , **UpperCamelCase__: int ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*_UpperCamelCase , **_UpperCamelCase ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: "Image" , UpperCamelCase__: str ): lowerCamelCase__ : List[str] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" lowerCamelCase__ : Optional[int] = task_prompt.replace("""{user_input}""" , _UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = self.pre_processor.tokenizer( _UpperCamelCase , add_special_tokens=_UpperCamelCase , return_tensors="""pt""" ).input_ids lowerCamelCase__ : Dict = self.pre_processor(_UpperCamelCase , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def lowerCamelCase_ ( self: int , UpperCamelCase__: Optional[Any] ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=_UpperCamelCase , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=_UpperCamelCase , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=_UpperCamelCase , ).sequences def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: List[Any] ): lowerCamelCase__ : Optional[int] = self.pre_processor.batch_decode(_UpperCamelCase )[0] lowerCamelCase__ : Dict = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) lowerCamelCase__ : Optional[int] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) lowerCamelCase__ : Optional[int] = re.sub(R"""<.*?>""" , """""" , _UpperCamelCase , count=1 ).strip() # remove first task start token lowerCamelCase__ : List[str] = self.pre_processor.tokenajson(_UpperCamelCase ) return sequence["answer"]
715
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str =logging.get_logger(__name__) _A : int ={ '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """roc_bert""" def __init__( self: Optional[Any] , UpperCamelCase__: Any=30_522 , UpperCamelCase__: Optional[Any]=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: Tuple=12 , UpperCamelCase__: Tuple=3_072 , UpperCamelCase__: str="gelu" , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Dict=512 , UpperCamelCase__: str=2 , UpperCamelCase__: str=0.02 , UpperCamelCase__: Tuple=1e-12 , UpperCamelCase__: Any=True , UpperCamelCase__: Union[str, Any]=0 , UpperCamelCase__: List[Any]="absolute" , UpperCamelCase__: Any=None , UpperCamelCase__: Any=True , UpperCamelCase__: Optional[int]=True , UpperCamelCase__: Union[str, Any]=768 , UpperCamelCase__: int=910 , UpperCamelCase__: Tuple=512 , UpperCamelCase__: int=24_858 , UpperCamelCase__: Optional[Any]=True , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : Tuple = num_attention_heads lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : List[Any] = use_cache lowerCamelCase__ : Tuple = enable_pronunciation lowerCamelCase__ : Union[str, Any] = enable_shape lowerCamelCase__ : Union[str, Any] = pronunciation_embed_dim lowerCamelCase__ : Any = pronunciation_vocab_size lowerCamelCase__ : int = shape_embed_dim lowerCamelCase__ : Tuple = shape_vocab_size lowerCamelCase__ : Optional[Any] = concat_input lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Dict = classifier_dropout super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _lowercase ( a__ , unittest.TestCase ): '''simple docstring''' a = DanceDiffusionPipeline a = UNCONDITIONAL_AUDIO_GENERATION_PARAMS a = PipelineTesterMixin.required_optional_params - { """callback""", """latents""", """callback_steps""", """output_type""", """num_images_per_prompt""", } a = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS a = False a = False def lowerCamelCase_ ( self: List[str] ): torch.manual_seed(0 ) lowerCamelCase__ : List[Any] = UNetaDModel( block_out_channels=(32, 32, 64) , extra_in_channels=16 , sample_size=512 , sample_rate=16_000 , in_channels=2 , out_channels=2 , flip_sin_to_cos=_A , use_timestep_embedding=_A , time_embedding_type="""fourier""" , mid_block_type="""UNetMidBlock1D""" , down_block_types=("""DownBlock1DNoSkip""", """DownBlock1D""", """AttnDownBlock1D""") , up_block_types=("""AttnUpBlock1D""", """UpBlock1D""", """UpBlock1DNoSkip""") , ) lowerCamelCase__ : int = IPNDMScheduler() lowerCamelCase__ : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def lowerCamelCase_ ( self: Dict , UpperCamelCase__: str , UpperCamelCase__: Optional[int]=0 ): if str(_A ).startswith("""mps""" ): lowerCamelCase__ : str = torch.manual_seed(_A ) else: lowerCamelCase__ : Optional[Any] = torch.Generator(device=_A ).manual_seed(_A ) lowerCamelCase__ : int = { 'batch_size': 1, 'generator': generator, 'num_inference_steps': 4, } return inputs def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : int = self.get_dummy_components() lowerCamelCase__ : Optional[Any] = DanceDiffusionPipeline(**_A ) lowerCamelCase__ : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) lowerCamelCase__ : Union[str, Any] = self.get_dummy_inputs(_A ) lowerCamelCase__ : List[str] = pipe(**_A ) lowerCamelCase__ : List[Any] = output.audios lowerCamelCase__ : List[str] = audio[0, -3:, -3:] assert audio.shape == (1, 2, components["unet"].sample_size) lowerCamelCase__ : Optional[Any] = np.array([-0.7_265, 1.0_000, -0.8_388, 0.1_175, 0.9_498, -1.0_000] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCamelCase_ ( self: Any ): return super().test_save_load_local() @skip_mps def lowerCamelCase_ ( self: Optional[int] ): return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) @skip_mps def lowerCamelCase_ ( self: Optional[Any] ): return super().test_save_load_optional_components() @skip_mps def lowerCamelCase_ ( self: Any ): return super().test_attention_slicing_forward_pass() def lowerCamelCase_ ( self: str ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class _lowercase ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase_ ( self: List[str] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase_ ( self: str ): lowerCamelCase__ : List[Any] = torch_device lowerCamelCase__ : int = DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k""" ) lowerCamelCase__ : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) lowerCamelCase__ : Optional[int] = torch.manual_seed(0 ) lowerCamelCase__ : str = pipe(generator=_A , num_inference_steps=100 , audio_length_in_s=4.096 ) lowerCamelCase__ : str = output.audios lowerCamelCase__ : List[str] = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowerCamelCase__ : Union[str, Any] = np.array([-0.0_192, -0.0_231, -0.0_318, -0.0_059, 0.0_002, -0.0_020] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCamelCase_ ( self: str ): lowerCamelCase__ : str = torch_device lowerCamelCase__ : Tuple = DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k""" , torch_dtype=torch.floataa ) lowerCamelCase__ : Optional[int] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) lowerCamelCase__ : Union[str, Any] = torch.manual_seed(0 ) lowerCamelCase__ : Optional[int] = pipe(generator=_A , num_inference_steps=100 , audio_length_in_s=4.096 ) lowerCamelCase__ : Union[str, Any] = output.audios lowerCamelCase__ : int = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowerCamelCase__ : List[str] = np.array([-0.0_367, -0.0_488, -0.0_771, -0.0_525, -0.0_444, -0.0_341] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2
716
'''simple docstring''' import sys import turtle def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> None: my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( '''Correct format for using this script: ''' '''python fractals.py <int:depth_for_fractal>''' ) _A : Any =turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('''red''') _A : Dict =[(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
631
0
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _lowercase ( _A ): a = ["""image_processor""", """tokenizer"""] a = """BlipImageProcessor""" a = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self: int , UpperCamelCase__: Dict , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Dict = False super().__init__(__lowerCamelCase , __lowerCamelCase ) lowerCamelCase__ : int = self.image_processor def __call__( self: Tuple , UpperCamelCase__: ImageInput = None , UpperCamelCase__: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCamelCase__: bool = True , UpperCamelCase__: Union[bool, str, PaddingStrategy] = False , UpperCamelCase__: Union[bool, str, TruncationStrategy] = None , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: int = 0 , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[bool] = None , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = False , UpperCamelCase__: bool = True , UpperCamelCase__: Optional[Union[str, TensorType]] = None , **UpperCamelCase__: List[str] , ): if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: lowerCamelCase__ : Optional[int] = self.tokenizer lowerCamelCase__ : List[str] = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) return text_encoding # add pixel_values lowerCamelCase__ : Any = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase ) if text is not None: lowerCamelCase__ : Any = self.tokenizer( text=__lowerCamelCase , add_special_tokens=__lowerCamelCase , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=__lowerCamelCase , stride=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , return_overflowing_tokens=__lowerCamelCase , return_special_tokens_mask=__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , return_token_type_ids=__lowerCamelCase , return_length=__lowerCamelCase , verbose=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase , ) else: lowerCamelCase__ : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(__lowerCamelCase ) return encoding_image_processor def lowerCamelCase_ ( self: Optional[int] , *UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[Any] ): return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase ) def lowerCamelCase_ ( self: Union[str, Any] , *UpperCamelCase__: Dict , **UpperCamelCase__: Optional[Any] ): return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase ) @property def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Optional[int] = self.tokenizer.model_input_names lowerCamelCase__ : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
717
'''simple docstring''' from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class _lowercase : def __init__( self: int , UpperCamelCase__: Dict , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Union[str, Any]=7 , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: List[Any]=True , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: int=True , UpperCamelCase__: List[Any]=99 , UpperCamelCase__: Tuple=32 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Optional[int]=37 , UpperCamelCase__: Any="gelu" , UpperCamelCase__: Any=0.1 , UpperCamelCase__: int=0.1 , UpperCamelCase__: Optional[Any]=512 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Tuple=3 , UpperCamelCase__: Optional[int]=4 , UpperCamelCase__: Union[str, Any]=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Union[str, Any] = 13 lowerCamelCase__ : Any = 7 lowerCamelCase__ : int = True lowerCamelCase__ : Optional[Any] = True lowerCamelCase__ : Dict = True lowerCamelCase__ : List[str] = True lowerCamelCase__ : str = 99 lowerCamelCase__ : Dict = 384 lowerCamelCase__ : Optional[Any] = 2 lowerCamelCase__ : Optional[int] = 4 lowerCamelCase__ : Optional[Any] = 37 lowerCamelCase__ : Union[str, Any] = """gelu""" lowerCamelCase__ : int = 0.1 lowerCamelCase__ : Optional[Any] = 0.1 lowerCamelCase__ : List[Any] = 512 lowerCamelCase__ : Optional[Any] = 16 lowerCamelCase__ : Any = 2 lowerCamelCase__ : Optional[Any] = 0.02 lowerCamelCase__ : int = 3 lowerCamelCase__ : List[str] = 4 lowerCamelCase__ : Any = 128 lowerCamelCase__ : List[Any] = 2 lowerCamelCase__ : Optional[Any] = 9 lowerCamelCase__ : Any = 1 lowerCamelCase__ : Optional[int] = None def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : str = None if self.use_input_mask: lowerCamelCase__ : int = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : List[str] = None if self.use_token_type_ids: lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : int = None lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Any = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : List[Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCamelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: Any ): lowerCamelCase__ : List[Any] = TFConvBertModel(config=UpperCamelCase__ ) lowerCamelCase__ : str = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase__ : List[str] = [input_ids, input_mask] lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: Tuple , UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : int = TFConvBertForMaskedLM(config=UpperCamelCase__ ) lowerCamelCase__ : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : int = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : int = self.num_labels lowerCamelCase__ : Dict = TFConvBertForSequenceClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: Dict ): lowerCamelCase__ : Optional[int] = self.num_choices lowerCamelCase__ : Dict = TFConvBertForMultipleChoice(config=UpperCamelCase__ ) lowerCamelCase__ : int = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : List[str] = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Any = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Tuple = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Any , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: int ): lowerCamelCase__ : List[Any] = self.num_labels lowerCamelCase__ : List[str] = TFConvBertForTokenClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Optional[int] = TFConvBertForQuestionAnswering(config=UpperCamelCase__ ) lowerCamelCase__ : int = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : str = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : str = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a = ( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a = False a = False a = False def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Dict = TFConvBertModelTester(self ) lowerCamelCase__ : Dict = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: List[str] ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Dict = True lowerCamelCase__ : Tuple = True if hasattr(UpperCamelCase__ , """use_cache""" ): lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : List[str] = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Tuple = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) for model_class in self.all_model_classes: lowerCamelCase__ : int = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : Dict = len(model(UpperCamelCase__ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ , saved_model=UpperCamelCase__ ) lowerCamelCase__ : int = os.path.join(UpperCamelCase__ , """saved_model""" , """1""" ) lowerCamelCase__ : List[Any] = tf.keras.models.load_model(UpperCamelCase__ ) lowerCamelCase__ : Any = model(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : Dict = outputs["""encoder_hidden_states"""] lowerCamelCase__ : Any = outputs["""encoder_attentions"""] else: lowerCamelCase__ : int = outputs["""hidden_states"""] lowerCamelCase__ : Optional[int] = outputs["""attentions"""] self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Union[str, Any] = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) self.assertIsNotNone(UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : int = getattr(self.model_tester , """decoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Any = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Optional[int] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) def check_decoder_attentions_output(UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) self.assertEqual(out_len % 2 , 0 ) lowerCamelCase__ : Any = outputs.decoder_attentions self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(UpperCamelCase__: List[str] ): lowerCamelCase__ : Any = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: lowerCamelCase__ : int = True lowerCamelCase__ : Any = False lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = len(UpperCamelCase__ ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) lowerCamelCase__ : Tuple = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_decoder_attentions_output(UpperCamelCase__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Dict = model_class(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) # Check attention is always last and order is fine lowerCamelCase__ : List[Any] = True lowerCamelCase__ : int = True lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCamelCase__ ) ) self.assertEqual(model.config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) @require_tf class _lowercase ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) lowerCamelCase__ : Optional[Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ )[0] lowerCamelCase__ : Dict = [1, 6, 768] self.assertEqual(output.shape , UpperCamelCase__ ) lowerCamelCase__ : Dict = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCamelCase__ , atol=1e-4 )
631
0
'''simple docstring''' import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: def wrapper(*UpperCamelCase , **UpperCamelCase ): lowerCamelCase__ : int = timeit.default_timer() lowerCamelCase__ : Any = func(*a_ , **a_ ) lowerCamelCase__ : str = timeit.default_timer() - starttime return delta lowerCamelCase__ : int = func.__name__ return wrapper def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=100 , UpperCamelCase=None ) -> Tuple: lowerCamelCase__ : Union[str, Any] = [] lowerCamelCase__ : Optional[int] = seq_shapes or {} for i in range(a_ ): lowerCamelCase__ : List[Any] = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(a_ , _ArrayXD ): lowerCamelCase__ : Optional[Any] = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(a_ , datasets.Value ): if v.dtype == "string": lowerCamelCase__ : str = '''The small grey turtle was surprisingly fast when challenged.''' else: lowerCamelCase__ : Union[str, Any] = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(a_ , datasets.Sequence ): while isinstance(a_ , datasets.Sequence ): lowerCamelCase__ : Optional[int] = v.feature lowerCamelCase__ : List[Any] = seq_shapes[k] lowerCamelCase__ : Any = np.random.rand(*a_ ).astype(v.dtype ) lowerCamelCase__ : Tuple = data dummy_data.append((i, example) ) return dummy_data def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase=100 , UpperCamelCase=None ) -> str: lowerCamelCase__ : Optional[Any] = generate_examples(a_ , num_examples=a_ , seq_shapes=a_ ) with ArrowWriter(features=a_ , path=a_ ) as writer: for key, record in dummy_data: lowerCamelCase__ : int = features.encode_example(a_ ) writer.write(a_ ) lowerCamelCase__ : Any = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f'''Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.''' ) lowerCamelCase__ : Union[str, Any] = datasets.Dataset.from_file(filename=a_ , info=datasets.DatasetInfo(features=a_ ) ) return dataset
718
'''simple docstring''' _A : List[str] ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
631
0
'''simple docstring''' import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: lowerCamelCase__ : Optional[int] = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(_A , _A ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: lowerCamelCase__ , lowerCamelCase__ : List[str] = emb.weight.shape lowerCamelCase__ : int = nn.Linear(_A , _A , bias=_A ) lowerCamelCase__ : List[Any] = emb.weight.data return lin_layer def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=None ) -> Optional[int]: lowerCamelCase__ : List[Any] = {} for old_key in state_dict.keys(): lowerCamelCase__ : Optional[Any] = old_key if "moe_layer.experts." in key: if expert_idx is not None: lowerCamelCase__ : List[Any] = key.replace("""moe_layer.experts.0""" , f'''ffn.experts.expert_{expert_idx}''' ) else: lowerCamelCase__ : List[str] = key.replace("""moe_layer.experts.""" , """ffn.experts.expert_""" ) if "gate" in key: lowerCamelCase__ : Any = key.replace(""".moe_layer.gate.wg""" , """.ffn.router.classifier""" ) if "fc2" and "experts" not in key: lowerCamelCase__ : int = key.replace(""".fc2.""" , """.ffn.fc2.""" ) if "fc1" and "experts" not in key: lowerCamelCase__ : Dict = key.replace(""".fc1.""" , """.ffn.fc1.""" ) if ".encoder_attn." in key: lowerCamelCase__ : Union[str, Any] = key.replace(""".encoder_attn.""" , """.cross_attention.""" ) if "encoder_attn_layer_norm" in key: lowerCamelCase__ : int = key.replace("""encoder_attn_layer_norm""" , """cross_attention_layer_norm""" ) if "final_layer_norm" in key: lowerCamelCase__ : List[str] = key.replace("""final_layer_norm""" , """ff_layer_norm""" ) lowerCamelCase__ : int = state_dict[old_key] return new_dict def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = WEIGHTS_NAME ) -> str: lowerCamelCase__ : Dict = [] lowerCamelCase__ : int = 0 os.makedirs(_A , exist_ok=_A ) for expert in range(_A ): lowerCamelCase__ : str = switch_checkpoint_path + f'''-rank-{expert}.pt''' if os.path.isfile(_A ): lowerCamelCase__ : Any = torch.load(_A )["""model"""] remove_ignore_keys_(_A ) lowerCamelCase__ : Optional[int] = rename_fairseq_keys(_A , _A ) lowerCamelCase__ : Optional[int] = os.path.join( _A , weights_name.replace(""".bin""" , f'''-{len(_A )+1:05d}-of-???.bin''' ) ) torch.save(_A , _A ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(_A )[0]].dtype ) # Add the last block lowerCamelCase__ : Union[str, Any] = os.path.join(_A , weights_name.replace(""".bin""" , f'''-{len(_A )+1:05d}-of-???.bin''' ) ) lowerCamelCase__ : int = torch.load(switch_checkpoint_path + """-shared.pt""" )["""model"""] remove_ignore_keys_(_A ) lowerCamelCase__ : Optional[Any] = rename_fairseq_keys(_A , _A ) lowerCamelCase__ : int = shared_weights["""decoder.embed_tokens.weight"""] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(_A ) == 1: lowerCamelCase__ : List[str] = os.path.join(_A , _A ) torch.save(_A , _A ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(_A , _A ) # Otherwise, let's build the index lowerCamelCase__ : Union[str, Any] = {} for idx, shard in enumerate(_A ): lowerCamelCase__ : List[str] = weights_name.replace(""".bin""" , f'''-{idx+1:05d}-of-{len(_A ):05d}.bin''' ) lowerCamelCase__ : Union[str, Any] = os.path.join(_A , weights_name.replace(""".bin""" , f'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(_A , os.path.join(_A , _A ) ) for key in shard: lowerCamelCase__ : int = shard_file # Add the metadata lowerCamelCase__ : Tuple = {"""total_size""": total_size} lowerCamelCase__ : List[Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(_A , _A ) , """w""" , encoding="""utf-8""" ) as f: lowerCamelCase__ : Optional[Any] = json.dumps(_A , indent=2 , sort_keys=_A ) + """\n""" f.write(_A ) return metadata, index if __name__ == "__main__": _A : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--nllb_moe_checkpoint_path''', default='''/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--dtype''', default='''float32''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b''', type=str, required=False, help='''Path to the output pytorch model.''', ) _A : Optional[int] =parser.parse_args() _A : Optional[Any] =shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) _A : Union[str, Any] =NllbMoeConfig.from_pretrained( '''facebook/nllb-200-3.3B''', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) _A : Union[str, Any] =NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('''Done''') model.save_pretrained(args.pytorch_dump_folder_path)
719
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Any =logging.get_logger(__name__) _A : Dict ={ '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class _lowercase ( _lowercase ): a = """trocr""" a = ["""past_key_values"""] a = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Optional[Any] , UpperCamelCase__: int=50_265 , UpperCamelCase__: int=1_024 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Dict=16 , UpperCamelCase__: int=4_096 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: int=512 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Any=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: str=True , UpperCamelCase__: Tuple=False , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Tuple=True , UpperCamelCase__: Dict=1 , UpperCamelCase__: List[str]=0 , UpperCamelCase__: Union[str, Any]=2 , **UpperCamelCase__: str , ): lowerCamelCase__ : Any = vocab_size lowerCamelCase__ : Tuple = d_model lowerCamelCase__ : Any = decoder_layers lowerCamelCase__ : Dict = decoder_attention_heads lowerCamelCase__ : str = decoder_ffn_dim lowerCamelCase__ : Tuple = activation_function lowerCamelCase__ : Dict = max_position_embeddings lowerCamelCase__ : int = dropout lowerCamelCase__ : int = attention_dropout lowerCamelCase__ : List[Any] = activation_dropout lowerCamelCase__ : Union[str, Any] = init_std lowerCamelCase__ : Optional[int] = decoder_layerdrop lowerCamelCase__ : Dict = use_cache lowerCamelCase__ : Any = scale_embedding lowerCamelCase__ : Optional[int] = use_learned_position_embeddings lowerCamelCase__ : List[str] = layernorm_embedding super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
631
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _lowercase : @staticmethod def lowerCamelCase_ ( *UpperCamelCase__: str , **UpperCamelCase__: Any ): pass @is_pipeline_test @require_vision @require_timm @require_torch class _lowercase ( unittest.TestCase ): a = MODEL_FOR_OBJECT_DETECTION_MAPPING def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Dict = ObjectDetectionPipeline(model=snake_case_ , image_processor=snake_case_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def lowerCamelCase_ ( self: int , UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { """score""": ANY(snake_case_ ), """label""": ANY(snake_case_ ), """box""": {"""xmin""": ANY(snake_case_ ), """ymin""": ANY(snake_case_ ), """xmax""": ANY(snake_case_ ), """ymax""": ANY(snake_case_ )}, } , ) import datasets lowerCamelCase__ : Optional[Any] = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) lowerCamelCase__ : List[Any] = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] lowerCamelCase__ : int = object_detector(snake_case_ , threshold=0.0 ) self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for outputs in batch_outputs: self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { """score""": ANY(snake_case_ ), """label""": ANY(snake_case_ ), """box""": {"""xmin""": ANY(snake_case_ ), """ymin""": ANY(snake_case_ ), """xmax""": ANY(snake_case_ ), """ymax""": ANY(snake_case_ )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def lowerCamelCase_ ( self: List[Any] ): pass @require_torch def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : str = """hf-internal-testing/tiny-detr-mobilenetsv3""" lowerCamelCase__ : Dict = AutoModelForObjectDetection.from_pretrained(snake_case_ ) lowerCamelCase__ : Tuple = AutoFeatureExtractor.from_pretrained(snake_case_ ) lowerCamelCase__ : List[str] = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) lowerCamelCase__ : Tuple = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) lowerCamelCase__ : Union[str, Any] = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = """facebook/detr-resnet-50""" lowerCamelCase__ : Tuple = AutoModelForObjectDetection.from_pretrained(snake_case_ ) lowerCamelCase__ : List[Any] = AutoFeatureExtractor.from_pretrained(snake_case_ ) lowerCamelCase__ : str = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) lowerCamelCase__ : Any = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) lowerCamelCase__ : Optional[int] = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Optional[Any] = """facebook/detr-resnet-50""" lowerCamelCase__ : Optional[Any] = pipeline("""object-detection""" , model=snake_case_ ) lowerCamelCase__ : Dict = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) lowerCamelCase__ : Optional[Any] = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Optional[Any] = 0.9_985 lowerCamelCase__ : Optional[int] = """facebook/detr-resnet-50""" lowerCamelCase__ : Optional[int] = pipeline("""object-detection""" , model=snake_case_ ) lowerCamelCase__ : List[Any] = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=snake_case_ ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def lowerCamelCase_ ( self: str ): lowerCamelCase__ : List[Any] = """Narsil/layoutlmv3-finetuned-funsd""" lowerCamelCase__ : Any = 0.9_993 lowerCamelCase__ : Optional[int] = pipeline("""object-detection""" , model=snake_case_ , threshold=snake_case_ ) lowerCamelCase__ : Dict = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {"""score""": 0.9_993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9_993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
720
'''simple docstring''' # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : str = [False] * len(UpperCamelCase ) lowerCamelCase__ : str = [-1] * len(UpperCamelCase ) def dfs(UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Union[str, Any] = c for u in graph[v]: if not visited[u]: dfs(UpperCamelCase , 1 - c ) for i in range(len(UpperCamelCase ) ): if not visited[i]: dfs(UpperCamelCase , 0 ) for i in range(len(UpperCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph _A : int ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
631
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : Union[str, Any] ={ '''kssteven/ibert-roberta-base''': '''https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json''', '''kssteven/ibert-roberta-large''': '''https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json''', '''kssteven/ibert-roberta-large-mnli''': ( '''https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json''' ), } class _lowercase ( SCREAMING_SNAKE_CASE__ ): a = """ibert""" def __init__( self: Any , UpperCamelCase__: Dict=30_522 , UpperCamelCase__: Tuple=768 , UpperCamelCase__: Optional[int]=12 , UpperCamelCase__: Dict=12 , UpperCamelCase__: List[str]=3_072 , UpperCamelCase__: Optional[int]="gelu" , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: int=0.1 , UpperCamelCase__: Optional[Any]=512 , UpperCamelCase__: List[Any]=2 , UpperCamelCase__: Optional[int]=0.02 , UpperCamelCase__: Any=1e-12 , UpperCamelCase__: Union[str, Any]=1 , UpperCamelCase__: List[Any]=0 , UpperCamelCase__: Union[str, Any]=2 , UpperCamelCase__: Tuple="absolute" , UpperCamelCase__: str=False , UpperCamelCase__: Optional[Any]="none" , **UpperCamelCase__: Optional[int] , ): super().__init__(pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , **_lowercase ) lowerCamelCase__ : Dict = vocab_size lowerCamelCase__ : Tuple = hidden_size lowerCamelCase__ : List[Any] = num_hidden_layers lowerCamelCase__ : int = num_attention_heads lowerCamelCase__ : Tuple = hidden_act lowerCamelCase__ : Tuple = intermediate_size lowerCamelCase__ : int = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : List[Any] = type_vocab_size lowerCamelCase__ : str = initializer_range lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Union[str, Any] = quant_mode lowerCamelCase__ : List[str] = force_dequant class _lowercase ( SCREAMING_SNAKE_CASE__ ): @property def lowerCamelCase_ ( self: Any ): if self.task == "multiple-choice": lowerCamelCase__ : List[Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase__ : List[str] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
721
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Optional[int] = dataset lowerCamelCase__ : Optional[int] = process lowerCamelCase__ : List[str] = params def __len__( self: List[str] ): return len(self.dataset ) def __getitem__( self: Any , UpperCamelCase__: int ): lowerCamelCase__ : Dict = self.dataset[i] lowerCamelCase__ : Union[str, Any] = self.process(UpperCamelCase__ , **self.params ) return processed class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): lowerCamelCase__ : int = loader lowerCamelCase__ : str = infer lowerCamelCase__ : Optional[int] = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : int = loader_batch_size # Internal bookkeeping lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None def __len__( self: Dict ): return len(self.loader ) def __iter__( self: Optional[int] ): lowerCamelCase__ : List[Any] = iter(self.loader ) return self def lowerCamelCase_ ( self: Any ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowerCamelCase__ : str = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowerCamelCase__ : int = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first lowerCamelCase__ : str = element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : Tuple = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : List[str] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : int = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowerCamelCase__ : List[str] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : Optional[Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : int = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowerCamelCase__ : str = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowerCamelCase__ : Optional[int] = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def lowerCamelCase_ ( self: List[Any] ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowerCamelCase__ : Optional[Any] = next(self.iterator ) lowerCamelCase__ : List[str] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Optional[Any] = processed else: lowerCamelCase__ : Union[str, Any] = list(processed.keys() )[0] lowerCamelCase__ : Any = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Any = len(UpperCamelCase__ ) else: lowerCamelCase__ : List[str] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : Union[str, Any] = observed_batch_size # Setting internal index to unwrap the batch lowerCamelCase__ : List[Any] = processed lowerCamelCase__ : List[Any] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class _lowercase ( _lowercase ): def __init__( self: List[str] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any]=None ): super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self: Union[str, Any] ): lowerCamelCase__ : str = iter(self.loader ) lowerCamelCase__ : int = None return self def lowerCamelCase_ ( self: str ): if self.subiterator is None: lowerCamelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowerCamelCase__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowerCamelCase__ : Any = self.infer(next(self.iterator ) , **self.params ) lowerCamelCase__ : Union[str, Any] = next(self.subiterator ) return processed class _lowercase ( _lowercase ): def __iter__( self: List[Any] ): lowerCamelCase__ : int = iter(self.loader ) return self def lowerCamelCase_ ( self: Tuple ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowerCamelCase__ : List[str] = False lowerCamelCase__ : Union[str, Any] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : Any = self.loader_batch_item() lowerCamelCase__ : Tuple = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: lowerCamelCase__ : str = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Dict = processed else: lowerCamelCase__ : Dict = list(processed.keys() )[0] lowerCamelCase__ : Dict = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) else: lowerCamelCase__ : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : str = observed_batch_size lowerCamelCase__ : str = processed lowerCamelCase__ : Optional[int] = 0 while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : List[Any] = self.loader_batch_item() lowerCamelCase__ : str = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: lowerCamelCase__ : Optional[Any] = processed lowerCamelCase__ : Optional[int] = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) return accumulator class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str ): lowerCamelCase__ : Union[str, Any] = dataset lowerCamelCase__ : str = key def __len__( self: Optional[Any] ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Any ): return self.dataset[i][self.key] class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str , UpperCamelCase__: str ): lowerCamelCase__ : str = dataset lowerCamelCase__ : Dict = keya lowerCamelCase__ : List[str] = keya def __len__( self: str ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Union[str, Any] ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
631
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Any =logging.get_logger(__name__) _A : List[str] ={ '''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 _lowercase ( _lowercase ): a = '''dpr''' def __init__( self: Tuple , UpperCamelCase__: int=30_522 , UpperCamelCase__: int=768 , UpperCamelCase__: Any=12 , UpperCamelCase__: List[str]=12 , UpperCamelCase__: str=3_072 , UpperCamelCase__: Optional[Any]="gelu" , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: int=512 , UpperCamelCase__: Union[str, Any]=2 , UpperCamelCase__: Optional[int]=0.02 , UpperCamelCase__: List[Any]=1e-12 , UpperCamelCase__: str=0 , UpperCamelCase__: str="absolute" , UpperCamelCase__: int = 0 , **UpperCamelCase__: Union[str, Any] , ): super().__init__(pad_token_id=A_ , **A_ ) lowerCamelCase__ : Union[str, Any] = vocab_size lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : str = num_attention_heads lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : Optional[Any] = hidden_dropout_prob lowerCamelCase__ : int = attention_probs_dropout_prob lowerCamelCase__ : Optional[Any] = max_position_embeddings lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Optional[int] = initializer_range lowerCamelCase__ : List[Any] = layer_norm_eps lowerCamelCase__ : List[Any] = projection_dim lowerCamelCase__ : List[Any] = position_embedding_type
700
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys _A : Dict ='''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
631
0
'''simple docstring''' import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('''>=''', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType _A : Any =get_logger(__name__) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=0 ) -> int: os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) with FSDP.state_dict_type( __SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): lowerCamelCase__ : Optional[int] = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: lowerCamelCase__ : List[Any] = f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin''' lowerCamelCase__ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if accelerator.process_index == 0: logger.info(f'''Saving model to {output_model_file}''' ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: lowerCamelCase__ : Optional[int] = ( f'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) lowerCamelCase__ : Optional[int] = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Saving model to {output_model_file}''' ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Model saved to {output_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: lowerCamelCase__ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , f'''{MODEL_NAME}_{model_index}''' ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(f'''Saving model to {ckpt_dir}''' ) lowerCamelCase__ : Tuple = {"""model""": state_dict} dist_cp.save_state_dict( state_dict=__SCREAMING_SNAKE_CASE , storage_writer=dist_cp.FileSystemWriter(__SCREAMING_SNAKE_CASE ) , planner=DefaultSavePlanner() , ) logger.info(f'''Model saved to {ckpt_dir}''' ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=0 ) -> List[Any]: accelerator.wait_for_everyone() with FSDP.state_dict_type( __SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(__SCREAMING_SNAKE_CASE ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( """Set the `sync_module_states` flag to `True` so that model states are synced across processes when """ """initializing FSDP object""" ) return lowerCamelCase__ : Any = f'''{MODEL_NAME}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}.bin''' lowerCamelCase__ : Dict = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Loading model from {input_model_file}''' ) lowerCamelCase__ : Any = torch.load(__SCREAMING_SNAKE_CASE ) logger.info(f'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: lowerCamelCase__ : int = ( f'''{MODEL_NAME}_rank{accelerator.process_index}.bin''' if model_index == 0 else f'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin''' ) lowerCamelCase__ : int = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Loading model from {input_model_file}''' ) lowerCamelCase__ : List[str] = torch.load(__SCREAMING_SNAKE_CASE ) logger.info(f'''Model loaded from {input_model_file}''' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: lowerCamelCase__ : Optional[int] = ( os.path.join(__SCREAMING_SNAKE_CASE , f'''{MODEL_NAME}_{model_index}''' ) if f'''{MODEL_NAME}''' not in input_dir else input_dir ) logger.info(f'''Loading model from {ckpt_dir}''' ) lowerCamelCase__ : str = {"""model""": model.state_dict()} dist_cp.load_state_dict( state_dict=__SCREAMING_SNAKE_CASE , storage_reader=dist_cp.FileSystemReader(__SCREAMING_SNAKE_CASE ) , planner=DefaultLoadPlanner() , ) lowerCamelCase__ : Tuple = state_dict["""model"""] logger.info(f'''Model loaded from {ckpt_dir}''' ) model.load_state_dict(__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=0 ) -> Optional[Any]: os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) with FSDP.state_dict_type( __SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): lowerCamelCase__ : List[Any] = FSDP.optim_state_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: lowerCamelCase__ : str = ( f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) lowerCamelCase__ : List[str] = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Saving Optimizer state to {output_optimizer_file}''' ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Optimizer state saved in {output_optimizer_file}''' ) else: lowerCamelCase__ : int = os.path.join(__SCREAMING_SNAKE_CASE , f'''{OPTIMIZER_NAME}_{optimizer_index}''' ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) logger.info(f'''Saving Optimizer state to {ckpt_dir}''' ) dist_cp.save_state_dict( state_dict={"""optimizer""": optim_state} , storage_writer=dist_cp.FileSystemWriter(__SCREAMING_SNAKE_CASE ) , planner=DefaultSavePlanner() , ) logger.info(f'''Optimizer state saved in {ckpt_dir}''' ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=0 ) -> Optional[Any]: accelerator.wait_for_everyone() with FSDP.state_dict_type( __SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: lowerCamelCase__ : Dict = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: lowerCamelCase__ : List[str] = ( f'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else f'''{OPTIMIZER_NAME}_{optimizer_index}.bin''' ) lowerCamelCase__ : str = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) logger.info(f'''Loading Optimizer state from {input_optimizer_file}''' ) lowerCamelCase__ : str = torch.load(__SCREAMING_SNAKE_CASE ) logger.info(f'''Optimizer state loaded from {input_optimizer_file}''' ) else: lowerCamelCase__ : Any = ( os.path.join(__SCREAMING_SNAKE_CASE , f'''{OPTIMIZER_NAME}_{optimizer_index}''' ) if f'''{OPTIMIZER_NAME}''' not in input_dir else input_dir ) logger.info(f'''Loading Optimizer from {ckpt_dir}''' ) lowerCamelCase__ : Union[str, Any] = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="""optimizer""" , storage_reader=dist_cp.FileSystemReader(__SCREAMING_SNAKE_CASE ) , ) lowerCamelCase__ : Optional[int] = optim_state["""optimizer"""] logger.info(f'''Optimizer loaded from {ckpt_dir}''' ) lowerCamelCase__ : Dict = FSDP.optim_state_dict_to_load(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) optimizer.load_state_dict(__SCREAMING_SNAKE_CASE )
701
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _A : Any ={ '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : str =[ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _A : List[Any] =logging.get_logger(__name__) _A : Optional[int] ={ '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } _A : Any =[ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: for attribute in key.split(""".""" ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models lowerCamelCase__ : Optional[Any] = """lm_head""" lowerCamelCase__ : Any = getattr(UpperCamelCase , UpperCamelCase ) if weight_type is not None: lowerCamelCase__ : int = getattr(UpperCamelCase , UpperCamelCase ).shape else: lowerCamelCase__ : str = hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": lowerCamelCase__ : int = value elif weight_type == "weight_g": lowerCamelCase__ : str = value elif weight_type == "weight_v": lowerCamelCase__ : Tuple = value elif weight_type == "bias": lowerCamelCase__ : List[Any] = value else: lowerCamelCase__ : List[Any] = value logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[int]: lowerCamelCase__ : List[Any] = [] lowerCamelCase__ : Union[str, Any] = fairseq_model.state_dict() lowerCamelCase__ : List[str] = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): lowerCamelCase__ : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , hf_model.config.feat_extract_norm == """group""" , ) lowerCamelCase__ : Dict = True else: for key, mapped_key in MAPPING.items(): lowerCamelCase__ : Any = """unispeech.""" + 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]: lowerCamelCase__ : Dict = True if "*" in mapped_key: lowerCamelCase__ : Union[str, Any] = name.split(UpperCamelCase )[0].split(""".""" )[-2] lowerCamelCase__ : int = mapped_key.replace("""*""" , UpperCamelCase ) if "weight_g" in name: lowerCamelCase__ : Dict = """weight_g""" elif "weight_v" in name: lowerCamelCase__ : Optional[Any] = """weight_v""" elif "bias" in name: lowerCamelCase__ : Dict = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj lowerCamelCase__ : Optional[int] = """weight""" else: lowerCamelCase__ : List[str] = None set_recursively(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) continue if not is_used: unused_weights.append(UpperCamelCase ) logger.warning(f'''Unused weights: {unused_weights}''' ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[int]: lowerCamelCase__ : Tuple = full_name.split("""conv_layers.""" )[-1] lowerCamelCase__ : Union[str, Any] = name.split(""".""" ) lowerCamelCase__ : Optional[int] = int(items[0] ) lowerCamelCase__ : Optional[int] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) lowerCamelCase__ : Optional[Any] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) lowerCamelCase__ : Optional[Any] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) lowerCamelCase__ : List[Any] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) lowerCamelCase__ : Union[str, Any] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCamelCase ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=True ) -> Dict: if config_path is not None: lowerCamelCase__ : Optional[int] = UniSpeechConfig.from_pretrained(UpperCamelCase ) else: lowerCamelCase__ : str = UniSpeechConfig() if is_finetuned: if dict_path: lowerCamelCase__ : int = Dictionary.load_from_json(UpperCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowerCamelCase__ : str = target_dict.pad_index lowerCamelCase__ : Tuple = target_dict.bos_index lowerCamelCase__ : Optional[Any] = target_dict.eos_index lowerCamelCase__ : Dict = len(target_dict.symbols ) lowerCamelCase__ : int = os.path.join(UpperCamelCase , """vocab.json""" ) if not os.path.isdir(UpperCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(UpperCamelCase ) ) return os.makedirs(UpperCamelCase , exist_ok=UpperCamelCase ) lowerCamelCase__ : str = target_dict.indices # fairseq has the <pad> and <s> switched lowerCamelCase__ : List[Any] = 42 lowerCamelCase__ : Any = 43 with open(UpperCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : List[str] = WavaVecaPhonemeCTCTokenizer( UpperCamelCase , 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=UpperCamelCase , ) lowerCamelCase__ : str = True if config.feat_extract_norm == """layer""" else False lowerCamelCase__ : str = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=UpperCamelCase , return_attention_mask=UpperCamelCase , ) lowerCamelCase__ : Union[str, Any] = WavaVecaProcessor(feature_extractor=UpperCamelCase , tokenizer=UpperCamelCase ) processor.save_pretrained(UpperCamelCase ) lowerCamelCase__ : List[str] = UniSpeechForCTC(UpperCamelCase ) else: lowerCamelCase__ : List[Any] = UniSpeechForPreTraining(UpperCamelCase ) if is_finetuned: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} ) else: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) lowerCamelCase__ : Dict = model[0].eval() recursively_load_weights(UpperCamelCase , UpperCamelCase , UpperCamelCase ) hf_unispeech.save_pretrained(UpperCamelCase ) if __name__ == "__main__": _A : Optional[Any] =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''' ) _A : Tuple =parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
702
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : List[str] ={ '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """audio-spectrogram-transformer""" def __init__( self: str , UpperCamelCase__: Any=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: List[Any]=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: Optional[Any]="gelu" , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: Union[str, Any]=0.02 , UpperCamelCase__: Dict=1e-12 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=10 , UpperCamelCase__: List[str]=10 , UpperCamelCase__: Any=1_024 , UpperCamelCase__: Optional[Any]=128 , **UpperCamelCase__: Union[str, Any] , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : List[str] = num_attention_heads lowerCamelCase__ : Optional[int] = intermediate_size lowerCamelCase__ : List[Any] = hidden_act lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : str = attention_probs_dropout_prob lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[str] = layer_norm_eps lowerCamelCase__ : List[Any] = patch_size lowerCamelCase__ : List[str] = qkv_bias lowerCamelCase__ : Dict = frequency_stride lowerCamelCase__ : List[Any] = time_stride lowerCamelCase__ : str = max_length lowerCamelCase__ : Dict = num_mel_bins
631
0
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING _A : Optional[int] =logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase_ ) class _lowercase ( UpperCamelCase_ ): def __init__( self: str , *UpperCamelCase__: str , **UpperCamelCase__: Optional[Any] ): super().__init__(*__A , **__A ) requires_backends(self , """vision""" ) self.check_model_type(__A ) def __call__( self: List[Any] , UpperCamelCase__: Union[str, List[str], "Image.Image", List["Image.Image"]] , **UpperCamelCase__: Optional[int] ): return super().__call__(__A , **__A ) def lowerCamelCase_ ( self: List[str] , **UpperCamelCase__: Optional[Any] ): return {}, {}, {} def lowerCamelCase_ ( self: Dict , UpperCamelCase__: Tuple ): lowerCamelCase__ : Dict = load_image(__A ) lowerCamelCase__ : Tuple = image.size lowerCamelCase__ : Any = self.image_processor(images=__A , return_tensors=self.framework ) return model_inputs def lowerCamelCase_ ( self: int , UpperCamelCase__: Dict ): lowerCamelCase__ : Optional[Any] = self.model(**__A ) return model_outputs def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : str = model_outputs.predicted_depth lowerCamelCase__ : Optional[Any] = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode="""bicubic""" , align_corners=__A ) lowerCamelCase__ : List[Any] = prediction.squeeze().cpu().numpy() lowerCamelCase__ : str = (output * 255 / np.max(__A )).astype("""uint8""" ) lowerCamelCase__ : Any = Image.fromarray(__A ) lowerCamelCase__ : Dict = {} lowerCamelCase__ : Tuple = predicted_depth lowerCamelCase__ : Dict = depth return output_dict
703
'''simple docstring''' import argparse import os import re import packaging.version _A : List[str] ='''examples/''' _A : Any ={ '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } _A : int ={ '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } _A : int ='''README.md''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> str: with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : List[str] = f.read() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = REPLACE_PATTERNS[pattern] lowerCamelCase__ : Dict = replace.replace("""VERSION""" , UpperCamelCase ) lowerCamelCase__ : str = re_pattern.sub(UpperCamelCase , UpperCamelCase ) with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: for folder, directories, fnames in os.walk(UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(UpperCamelCase , UpperCamelCase ) , UpperCamelCase , pattern="""examples""" ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> List[Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if not patch: update_version_in_examples(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: lowerCamelCase__ : Dict = """🤗 Transformers currently provides the following architectures""" lowerCamelCase__ : Dict = """1. Want to contribute a new model?""" with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : int = f.readlines() # Find the start of the list. lowerCamelCase__ : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowerCamelCase__ : Optional[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): lowerCamelCase__ : List[Any] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: lowerCamelCase__ : int = f.read() lowerCamelCase__ : Optional[Any] = REPLACE_PATTERNS["""init"""][0].search(UpperCamelCase ).groups()[0] return packaging.version.parse(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase=False ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: lowerCamelCase__ : List[str] = default_version.base_version elif patch: lowerCamelCase__ : Any = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowerCamelCase__ : List[Any] = f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowerCamelCase__ : Any = input(f'''Which version are you releasing? [{default_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Optional[int] = default_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase , patch=UpperCamelCase ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def SCREAMING_SNAKE_CASE_ () -> List[str]: lowerCamelCase__ : Optional[int] = get_version() lowerCamelCase__ : Any = f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowerCamelCase__ : Any = current_version.base_version # Check with the user we got that right. lowerCamelCase__ : List[Any] = input(f'''Which version are we developing now? [{dev_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Dict = dev_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') _A : List[str] =parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
631
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 100 ) -> str: lowerCamelCase__ : Dict = n * (n + 1) * (2 * n + 1) / 6 lowerCamelCase__ : Dict = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'{solution() = }')
704
'''simple docstring''' import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow _A : Union[str, Any] =False class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: Dict , UpperCamelCase__: str=32 ): set_seed(0 ) lowerCamelCase__ : Optional[int] = UNetaDModel(sample_size=UpperCamelCase__ , in_channels=3 , out_channels=3 ) lowerCamelCase__ : List[Any] = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Optional[Any] = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCamelCase__ : List[Any] = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) lowerCamelCase__ : Any = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCamelCase__ : str = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randn((4, 3, 32, 32) ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randint(0 , 1_000 , (4,) ).long().to(UpperCamelCase__ ) for _ in range(4 )] # train with a DDPM scheduler lowerCamelCase__ , lowerCamelCase__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : str = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : str = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Tuple = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : Dict = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Union[str, Any] = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) )
631
0
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: # Checks if the entire collection has been sorted if len(UpperCamelCase ) <= 1 or n <= 1: return insert_next(UpperCamelCase , n - 1 ) rec_insertion_sort(UpperCamelCase , n - 1 ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Dict: # Checks order between adjacent elements if index >= len(UpperCamelCase ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order lowerCamelCase__ : Dict = ( collection[index], collection[index - 1], ) insert_next(UpperCamelCase , index + 1 ) if __name__ == "__main__": _A : str =input('''Enter integers separated by spaces: ''') _A : Optional[Any] =[int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
705
'''simple docstring''' from statistics import mean import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : Optional[int] = 0 # Number of processes finished lowerCamelCase__ : Union[str, Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowerCamelCase__ : Tuple = [0] * no_of_process # List to include calculation results lowerCamelCase__ : List[str] = [0] * no_of_process # Sort by arrival time. lowerCamelCase__ : Union[str, Any] = [burst_time[i] for i in np.argsort(UpperCamelCase )] lowerCamelCase__ : List[Any] = [process_name[i] for i in np.argsort(UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: lowerCamelCase__ : str = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowerCamelCase__ : Union[str, Any] = arrival_time[i] lowerCamelCase__ : Any = 0 # Index showing the location of the process being performed lowerCamelCase__ : Union[str, Any] = 0 # Saves the current response ratio. lowerCamelCase__ : Any = 0 for i in range(0 , UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowerCamelCase__ : Optional[int] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowerCamelCase__ : int = temp lowerCamelCase__ : str = i # Calculate the turn around time lowerCamelCase__ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowerCamelCase__ : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : int = [0] * no_of_process for i in range(0 , UpperCamelCase ): lowerCamelCase__ : Optional[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _A : List[str] =5 _A : Optional[Any] =['''A''', '''B''', '''C''', '''D''', '''E'''] _A : Optional[int] =[1, 2, 3, 4, 5] _A : Dict =[1, 2, 3, 4, 5] _A : Any =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _A : Optional[int] =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
631
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 1000 ) -> List[Any]: return sum(e for e in range(3 , snake_case__ ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(F'{solution() = }')
706
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
631
0
'''simple docstring''' import os from datetime import datetime as dt from github import Github _A : List[Any] =[ '''good first issue''', '''feature request''', '''wip''', ] def SCREAMING_SNAKE_CASE_ () -> str: lowerCamelCase__ : Union[str, Any] = Github(os.environ["""GITHUB_TOKEN"""] ) lowerCamelCase__ : Optional[Any] = g.get_repo("""huggingface/accelerate""" ) lowerCamelCase__ : Union[str, Any] = repo.get_issues(state="""open""" ) for issue in open_issues: lowerCamelCase__ : Optional[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda UpperCamelCase : i.created_at , reverse=__snake_case ) lowerCamelCase__ : int = comments[0] if len(__snake_case ) > 0 else None lowerCamelCase__ : str = dt.utcnow() lowerCamelCase__ : Any = (current_time - issue.updated_at).days lowerCamelCase__ : List[Any] = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state="""closed""" ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment 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/accelerate/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) if __name__ == "__main__": main()
707
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowercase : def __init__( self: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Optional[int]=30 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: List[str]=3 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=True , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Any=5 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Dict=37 , UpperCamelCase__: List[Any]="gelu" , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: List[Any]=10 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Optional[int]=3 , UpperCamelCase__: Dict=0.6 , UpperCamelCase__: int=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Optional[Any] = patch_size lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Any = is_training lowerCamelCase__ : Union[str, Any] = use_labels lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Any = hidden_dropout_prob lowerCamelCase__ : Optional[int] = attention_probs_dropout_prob lowerCamelCase__ : List[Any] = type_sequence_label_size lowerCamelCase__ : int = initializer_range lowerCamelCase__ : List[str] = mask_ratio lowerCamelCase__ : List[Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowerCamelCase__ : str = (image_size // patch_size) ** 2 lowerCamelCase__ : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: str ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int ): lowerCamelCase__ : Tuple = ViTMAEModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : List[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): lowerCamelCase__ : int = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Any = (self.image_size // self.patch_size) ** 2 lowerCamelCase__ : str = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowerCamelCase__ : Dict = 1 lowerCamelCase__ : Optional[int] = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = config_and_inputs lowerCamelCase__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () a = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} a = False a = False a = False a = False def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Tuple = ViTMAEModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase_ ( self: Dict ): pass def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Any = model_class(UpperCamelCase__ ) lowerCamelCase__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Any = [*signature.parameters.keys()] lowerCamelCase__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] ): # make masks reproducible np.random.seed(2 ) lowerCamelCase__ : Tuple = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) lowerCamelCase__ : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCamelCase__ : Tuple = torch.from_numpy(UpperCamelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowerCamelCase__ : Tuple = pt_noise super().check_pt_tf_models(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Optional[int] = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs[0].cpu().numpy() lowerCamelCase__ : List[str] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model_class.from_pretrained(UpperCamelCase__ ) model.to(UpperCamelCase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) # Make sure we don't have nans lowerCamelCase__ : Dict = after_outputs[0].cpu().numpy() lowerCamelCase__ : Tuple = 0 lowerCamelCase__ : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase__ , 1e-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: Any ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase_ ( self: Tuple ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Optional[int] ): pass @slow def lowerCamelCase_ ( self: List[str] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Tuple = ViTMAEModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> List[Any]: lowerCamelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: List[str] ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self: Tuple ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) lowerCamelCase__ : str = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : int = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowerCamelCase__ : List[str] = ViTMAEConfig() lowerCamelCase__ : int = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowerCamelCase__ : Any = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ , noise=torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ ) ) # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : str = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCamelCase__ ) , atol=1e-4 ) )
631
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowercase : a = PegasusConfig a = {} a = """gelu""" def __init__( self: List[Any] , UpperCamelCase__: int , UpperCamelCase__: Optional[int]=13 , UpperCamelCase__: Dict=7 , UpperCamelCase__: Tuple=True , UpperCamelCase__: List[str]=False , UpperCamelCase__: Dict=99 , UpperCamelCase__: Any=32 , UpperCamelCase__: Union[str, Any]=2 , UpperCamelCase__: str=4 , UpperCamelCase__: Optional[int]=37 , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Optional[int]=40 , UpperCamelCase__: Any=2 , UpperCamelCase__: Optional[int]=1 , UpperCamelCase__: int=0 , ): lowerCamelCase__ : int = parent lowerCamelCase__ : int = batch_size lowerCamelCase__ : str = seq_length lowerCamelCase__ : List[Any] = is_training lowerCamelCase__ : List[Any] = use_labels lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : Optional[Any] = num_hidden_layers lowerCamelCase__ : Optional[int] = num_attention_heads lowerCamelCase__ : Tuple = intermediate_size lowerCamelCase__ : Optional[int] = hidden_dropout_prob lowerCamelCase__ : Optional[Any] = attention_probs_dropout_prob lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : Union[str, Any] = eos_token_id lowerCamelCase__ : Any = pad_token_id lowerCamelCase__ : Tuple = bos_token_id def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCamelCase__ : int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCamelCase__ : Dict = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCamelCase__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : List[str] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowerCamelCase__ : int = prepare_pegasus_inputs_dict(lowercase_ , lowercase_ , lowercase_ ) return config, inputs_dict def lowerCamelCase_ ( self: int , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : Any = TFPegasusModel(config=lowercase_ ).get_decoder() lowerCamelCase__ : Optional[Any] = inputs_dict["""input_ids"""] lowerCamelCase__ : Dict = input_ids[:1, :] lowerCamelCase__ : int = inputs_dict["""attention_mask"""][:1, :] lowerCamelCase__ : Dict = inputs_dict["""head_mask"""] lowerCamelCase__ : str = 1 # first forward pass lowerCamelCase__ : Optional[Any] = model(lowercase_ , attention_mask=lowercase_ , head_mask=lowercase_ , use_cache=lowercase_ ) lowerCamelCase__ : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCamelCase__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCamelCase__ : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCamelCase__ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCamelCase__ : Optional[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCamelCase__ : int = model(lowercase_ , attention_mask=lowercase_ )[0] lowerCamelCase__ : int = 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 lowerCamelCase__ : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCamelCase__ : int = output_from_no_past[:, -3:, random_slice_idx] lowerCamelCase__ : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase_ , lowercase_ , rtol=1e-3 ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , ) -> Dict: if attention_mask is None: lowerCamelCase__ : List[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCamelCase__ : int = 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: lowerCamelCase__ : Optional[int] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCamelCase__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCamelCase__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowercase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): a = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () a = (TFPegasusForConditionalGeneration,) if is_tf_available() else () a = ( { """conversational""": TFPegasusForConditionalGeneration, """feature-extraction""": TFPegasusModel, """summarization""": TFPegasusForConditionalGeneration, """text2text-generation""": TFPegasusForConditionalGeneration, """translation""": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) a = True a = False a = False def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = TFPegasusModelTester(self ) lowerCamelCase__ : Any = ConfigTester(self , config_class=lowercase_ ) def lowerCamelCase_ ( self: Dict ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase_ ) @require_sentencepiece @require_tokenizers @require_tf class _lowercase ( unittest.TestCase ): a = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning \'Oh I think you\'re nominated\'\", said Dappy.\"And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around.\"At the end of the day we\'re grateful to be where we are in our careers.\"If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] a = [ """California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to""" """ reduce the risk of wildfires.""", """N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.""", ] # differs slightly from pytorch, likely due to numerical differences in linear layers a = """google/pegasus-xsum""" @cached_property def lowerCamelCase_ ( self: Dict ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Any = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def lowerCamelCase_ ( self: Union[str, Any] , **UpperCamelCase__: Any ): lowerCamelCase__ : List[Any] = self.translate_src_text(**lowercase_ ) assert self.expected_text == generated_words def lowerCamelCase_ ( self: Union[str, Any] , **UpperCamelCase__: List[Any] ): lowerCamelCase__ : Optional[Any] = self.tokenizer(self.src_text , **lowercase_ , padding=lowercase_ , return_tensors="""tf""" ) lowerCamelCase__ : int = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase_ , ) lowerCamelCase__ : Union[str, Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase_ ) return generated_words @slow def lowerCamelCase_ ( self: Any ): self._assert_generated_batch_equal_expected()
708
'''simple docstring''' import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _lowercase ( _lowercase ): a = """""" a = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a = None # compression type in fsspec. ex: "gzip" a = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self: str , UpperCamelCase__: str = "" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , **UpperCamelCase__: List[Any] ): super().__init__(self , **UpperCamelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode lowerCamelCase__ : List[Any] = fsspec.open( UpperCamelCase__ , mode="""rb""" , protocol=UpperCamelCase__ , compression=self.compression , client_kwargs={ """requote_redirect_url""": False, # see https://github.com/huggingface/datasets/pull/5459 """trust_env""": True, # Enable reading proxy env variables. **(target_options or {}).pop("""client_kwargs""" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) lowerCamelCase__ : str = os.path.basename(self.file.path.split("""::""" )[0] ) lowerCamelCase__ : Union[str, Any] = ( self.compressed_name[: self.compressed_name.rindex(""".""" )] if """.""" in self.compressed_name else self.compressed_name ) lowerCamelCase__ : Tuple = None @classmethod def lowerCamelCase_ ( cls: Optional[int] , UpperCamelCase__: Optional[int] ): # compressed file paths are always relative to the archive root return super()._strip_protocol(UpperCamelCase__ ).lstrip("""/""" ) def lowerCamelCase_ ( self: Tuple ): if self.dir_cache is None: lowerCamelCase__ : Dict = {**self.file.fs.info(self.file.path ), """name""": self.uncompressed_name} lowerCamelCase__ : int = {f["""name"""]: f} def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: str ): return self.file.open().read() def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[int]=None , UpperCamelCase__: Tuple=True , UpperCamelCase__: Tuple=None , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Union[str, Any] = self._strip_protocol(UpperCamelCase__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class _lowercase ( _lowercase ): a = """bz2""" a = """bz2""" a = """.bz2""" class _lowercase ( _lowercase ): a = """gzip""" a = """gzip""" a = """.gz""" class _lowercase ( _lowercase ): a = """lz4""" a = """lz4""" a = """.lz4""" class _lowercase ( _lowercase ): a = """xz""" a = """xz""" a = """.xz""" class _lowercase ( _lowercase ): a = """zstd""" a = """zstd""" a = """.zst""" def __init__( self: int , UpperCamelCase__: str , UpperCamelCase__: str = "rb" , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[dict] = None , UpperCamelCase__: int = DEFAULT_BLOCK_SIZE , **UpperCamelCase__: Dict , ): super().__init__( fo=UpperCamelCase__ , mode=UpperCamelCase__ , target_protocol=UpperCamelCase__ , target_options=UpperCamelCase__ , block_size=UpperCamelCase__ , **UpperCamelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 lowerCamelCase__ : Tuple = self.file.__enter__ class _lowercase : def __init__( self: Optional[int] , UpperCamelCase__: Any ): lowerCamelCase__ : Optional[int] = file_ def __enter__( self: List[Any] ): self._file.__enter__() return self def __exit__( self: Any , *UpperCamelCase__: str , **UpperCamelCase__: Any ): self._file.__exit__(*UpperCamelCase__ , **UpperCamelCase__ ) def __iter__( self: Any ): return iter(self._file ) def lowerCamelCase_ ( self: List[Any] ): return next(self._file ) def __getattr__( self: List[str] , UpperCamelCase__: Dict ): return getattr(self._file , UpperCamelCase__ ) def fixed_enter(*UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[str] ): return WrappedFile(_enter(*UpperCamelCase__ , **UpperCamelCase__ ) ) lowerCamelCase__ : Optional[Any] = fixed_enter
631
0
'''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 _A : Union[str, Any] =logging.get_logger(__name__) _A : Optional[Any] ={ '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class _lowercase ( a__ ): a = """yolos""" def __init__( self: Union[str, Any] , UpperCamelCase__: List[Any]=768 , UpperCamelCase__: int=12 , UpperCamelCase__: str=12 , UpperCamelCase__: str=3_072 , UpperCamelCase__: Optional[int]="gelu" , UpperCamelCase__: Dict=0.0 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: List[str]=1e-12 , UpperCamelCase__: int=[512, 864] , UpperCamelCase__: int=16 , UpperCamelCase__: List[str]=3 , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: List[Any]=100 , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Any=False , UpperCamelCase__: Dict=1 , UpperCamelCase__: List[Any]=5 , UpperCamelCase__: Any=2 , UpperCamelCase__: List[Any]=5 , UpperCamelCase__: Tuple=2 , UpperCamelCase__: Tuple=0.1 , **UpperCamelCase__: Any , ): super().__init__(**lowerCAmelCase__ ) lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : Optional[Any] = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : int = intermediate_size lowerCamelCase__ : int = hidden_act lowerCamelCase__ : int = hidden_dropout_prob lowerCamelCase__ : Optional[int] = attention_probs_dropout_prob lowerCamelCase__ : Tuple = initializer_range lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : Any = image_size lowerCamelCase__ : Optional[int] = patch_size lowerCamelCase__ : str = num_channels lowerCamelCase__ : Dict = qkv_bias lowerCamelCase__ : Union[str, Any] = num_detection_tokens lowerCamelCase__ : Optional[Any] = use_mid_position_embeddings lowerCamelCase__ : List[Any] = auxiliary_loss # Hungarian matcher lowerCamelCase__ : int = class_cost lowerCamelCase__ : str = bbox_cost lowerCamelCase__ : List[Any] = giou_cost # Loss coefficients lowerCamelCase__ : List[str] = bbox_loss_coefficient lowerCamelCase__ : Any = giou_loss_coefficient lowerCamelCase__ : Optional[Any] = eos_coefficient class _lowercase ( a__ ): a = version.parse("""1.11""" ) @property def lowerCamelCase_ ( self: List[Any] ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCamelCase_ ( self: int ): return 1e-4 @property def lowerCamelCase_ ( self: int ): return 12
709
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() _A : int =logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: print("""Loading config file...""" ) def flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase="" , UpperCamelCase="." ): lowerCamelCase__ : Optional[int] = [] for k, v in d.items(): lowerCamelCase__ : Optional[int] = parent_key + sep + k if parent_key else k if isinstance(UpperCamelCase , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(UpperCamelCase , UpperCamelCase , sep=UpperCamelCase ).items() ) else: items.append((new_key, v) ) return dict(UpperCamelCase ) lowerCamelCase__ : Any = argparse.Namespace() with open(UpperCamelCase , """r""" ) as yaml_file: try: lowerCamelCase__ : int = yaml.load(UpperCamelCase , Loader=yaml.FullLoader ) lowerCamelCase__ : Tuple = flatten_yaml_as_dict(UpperCamelCase ) for k, v in flat_cfg.items(): setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) except yaml.YAMLError as exc: logger.error("""Error while loading config file: {}. Error message: {}""".format(UpperCamelCase , str(UpperCamelCase ) ) ) return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Union[str, Any] = MobileViTVaConfig() lowerCamelCase__ : str = False # dataset if task_name.startswith("""imagenet1k_""" ): lowerCamelCase__ : Optional[Any] = 1000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : int = 384 else: lowerCamelCase__ : Optional[int] = 256 lowerCamelCase__ : str = """imagenet-1k-id2label.json""" elif task_name.startswith("""imagenet21k_to_1k_""" ): lowerCamelCase__ : Tuple = 21000 if int(task_name.strip().split("""_""" )[-1] ) == 384: lowerCamelCase__ : str = 384 else: lowerCamelCase__ : Any = 256 lowerCamelCase__ : int = """imagenet-22k-id2label.json""" elif task_name.startswith("""ade20k_""" ): lowerCamelCase__ : Dict = 151 lowerCamelCase__ : str = 512 lowerCamelCase__ : List[Any] = """ade20k-id2label.json""" lowerCamelCase__ : Union[str, Any] = True elif task_name.startswith("""voc_""" ): lowerCamelCase__ : Tuple = 21 lowerCamelCase__ : Optional[int] = 512 lowerCamelCase__ : List[Any] = """pascal-voc-id2label.json""" lowerCamelCase__ : Tuple = True # orig_config lowerCamelCase__ : Optional[int] = load_orig_config_file(UpperCamelCase ) assert getattr(UpperCamelCase , """model.classification.name""" , -1 ) == "mobilevit_v2", "Invalid model" lowerCamelCase__ : int = getattr(UpperCamelCase , """model.classification.mitv2.width_multiplier""" , 1.0 ) assert ( getattr(UpperCamelCase , """model.classification.mitv2.attn_norm_layer""" , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.classification.activation.name""" , """swish""" ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: lowerCamelCase__ : Any = getattr(UpperCamelCase , """model.segmentation.output_stride""" , 16 ) if "_deeplabv3" in task_name: lowerCamelCase__ : str = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_rates""" , [12, 24, 36] ) lowerCamelCase__ : Tuple = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_out_channels""" , 512 ) lowerCamelCase__ : List[Any] = getattr(UpperCamelCase , """model.segmentation.deeplabv3.aspp_dropout""" , 0.1 ) # id2label lowerCamelCase__ : Tuple = """huggingface/label-files""" lowerCamelCase__ : Optional[Any] = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) lowerCamelCase__ : Union[str, Any] = {int(UpperCamelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : int = idalabel lowerCamelCase__ : Optional[Any] = {v: k for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any: lowerCamelCase__ : List[Any] = dct.pop(UpperCamelCase ) lowerCamelCase__ : Dict = val def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> Tuple: if base_model: lowerCamelCase__ : Optional[int] = """""" else: lowerCamelCase__ : Optional[Any] = """mobilevitv2.""" lowerCamelCase__ : List[str] = [] for k in state_dict.keys(): if k[:8] == "encoder.": lowerCamelCase__ : Optional[Any] = k[8:] else: lowerCamelCase__ : Optional[Any] = k if ".block." in k: lowerCamelCase__ : Dict = k_new.replace(""".block.""" , """.""" ) if ".conv." in k: lowerCamelCase__ : List[Any] = k_new.replace(""".conv.""" , """.convolution.""" ) if ".norm." in k: lowerCamelCase__ : str = k_new.replace(""".norm.""" , """.normalization.""" ) if "conv_1." in k: lowerCamelCase__ : Any = k_new.replace("""conv_1.""" , f'''{model_prefix}conv_stem.''' ) for i in [1, 2]: if f'''layer_{i}.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.''' , f'''{model_prefix}encoder.layer.{i-1}.layer.''' ) if ".exp_1x1." in k: lowerCamelCase__ : Dict = k_new.replace(""".exp_1x1.""" , """.expand_1x1.""" ) if ".red_1x1." in k: lowerCamelCase__ : str = k_new.replace(""".red_1x1.""" , """.reduce_1x1.""" ) for i in [3, 4, 5]: if f'''layer_{i}.0.''' in k: lowerCamelCase__ : List[str] = k_new.replace(f'''layer_{i}.0.''' , f'''{model_prefix}encoder.layer.{i-1}.downsampling_layer.''' ) if f'''layer_{i}.1.local_rep.0.''' in k: lowerCamelCase__ : Optional[Any] = k_new.replace(f'''layer_{i}.1.local_rep.0.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_kxk.''' ) if f'''layer_{i}.1.local_rep.1.''' in k: lowerCamelCase__ : Dict = k_new.replace(f'''layer_{i}.1.local_rep.1.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_1x1.''' ) for i in [3, 4, 5]: if i == 3: lowerCamelCase__ : int = [0, 1] elif i == 4: lowerCamelCase__ : str = [0, 1, 2, 3] elif i == 5: lowerCamelCase__ : Dict = [0, 1, 2] for j in j_in: if f'''layer_{i}.1.global_rep.{j}.''' in k: lowerCamelCase__ : List[Any] = k_new.replace( f'''layer_{i}.1.global_rep.{j}.''' , f'''{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.''' ) if f'''layer_{i}.1.global_rep.{j+1}.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace( f'''layer_{i}.1.global_rep.{j+1}.''' , f'''{model_prefix}encoder.layer.{i-1}.layernorm.''' ) if f'''layer_{i}.1.conv_proj.''' in k: lowerCamelCase__ : Optional[int] = k_new.replace(f'''layer_{i}.1.conv_proj.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_projection.''' ) if "pre_norm_attn.0." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.0.""" , """layernorm_before.""" ) if "pre_norm_attn.1." in k: lowerCamelCase__ : str = k_new.replace("""pre_norm_attn.1.""" , """attention.""" ) if "pre_norm_ffn.0." in k: lowerCamelCase__ : Optional[Any] = k_new.replace("""pre_norm_ffn.0.""" , """layernorm_after.""" ) if "pre_norm_ffn.1." in k: lowerCamelCase__ : Union[str, Any] = k_new.replace("""pre_norm_ffn.1.""" , """ffn.conv1.""" ) if "pre_norm_ffn.3." in k: lowerCamelCase__ : List[Any] = k_new.replace("""pre_norm_ffn.3.""" , """ffn.conv2.""" ) if "classifier.1." in k: lowerCamelCase__ : Tuple = k_new.replace("""classifier.1.""" , """classifier.""" ) if "seg_head." in k: lowerCamelCase__ : Optional[int] = k_new.replace("""seg_head.""" , """segmentation_head.""" ) if ".aspp_layer." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_layer.""" , """.""" ) if ".aspp_pool." in k: lowerCamelCase__ : Any = k_new.replace(""".aspp_pool.""" , """.""" ) rename_keys.append((k, k_new) ) return rename_keys def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: lowerCamelCase__ : Union[str, Any] = [] for k in state_dict.keys(): if k.startswith("""seg_head.aux_head.""" ): keys_to_ignore.append(UpperCamelCase ) for k in keys_to_ignore: state_dict.pop(UpperCamelCase , UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Dict: lowerCamelCase__ : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" lowerCamelCase__ : Tuple = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCamelCase__ : str = get_mobilevitva_config(UpperCamelCase , UpperCamelCase ) # load original state_dict lowerCamelCase__ : List[str] = torch.load(UpperCamelCase , map_location="""cpu""" ) # load huggingface model if task_name.startswith("""ade20k_""" ) or task_name.startswith("""voc_""" ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation(UpperCamelCase ).eval() lowerCamelCase__ : Tuple = False else: lowerCamelCase__ : int = MobileViTVaForImageClassification(UpperCamelCase ).eval() lowerCamelCase__ : Optional[Any] = False # remove and rename some keys of load the original model lowerCamelCase__ : Tuple = checkpoint remove_unused_keys(UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = create_rename_keys(UpperCamelCase , base_model=UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # load modified state_dict model.load_state_dict(UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor lowerCamelCase__ : int = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) lowerCamelCase__ : Dict = image_processor(images=prepare_img() , return_tensors="""pt""" ) lowerCamelCase__ : str = model(**UpperCamelCase ) # verify classification model if task_name.startswith("""imagenet""" ): lowerCamelCase__ : Dict = outputs.logits lowerCamelCase__ : Optional[Any] = logits.argmax(-1 ).item() print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] ) if task_name.startswith("""imagenet1k_256""" ) and config.width_multiplier == 1.0: # expected_logits for base variant lowerCamelCase__ : Optional[Any] = torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01] ) assert torch.allclose(logits[0, :3] , UpperCamelCase , atol=1E-4 ) Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(f'''Saving model {task_name} 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 __name__ == "__main__": _A : Optional[int] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''imagenet1k_256''', type=str, help=( '''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ''' ''' Classification (ImageNet-1k) - MobileViTV2 (256x256) : imagenet1k_256 - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384 - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) : imagenet21k_to_1k_256 - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on ImageNet-1k 384x384) : imagenet21k_to_1k_384 Segmentation - ADE20K Dataset : ade20k_deeplabv3 - Pascal VOC 2012 Dataset: voc_deeplabv3 ''' ), choices=[ '''imagenet1k_256''', '''imagenet1k_384''', '''imagenet21k_to_1k_256''', '''imagenet21k_to_1k_384''', '''ade20k_deeplabv3''', '''voc_deeplabv3''', ], ) parser.add_argument( '''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).''' ) parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.''' ) _A : Dict =parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
631
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _A : int =logging.getLogger(__name__) @dataclass class _lowercase : a = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a = field( default=UpperCAmelCase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) a = field( default=UpperCAmelCase__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a = field(default=UpperCAmelCase__ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. a = field( default=UpperCAmelCase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class _lowercase : a = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) a = field( default=UpperCAmelCase__ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) a = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a = field( default=UpperCAmelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def SCREAMING_SNAKE_CASE_ () -> int: lowerCamelCase__ : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Optional[int] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' """ --overwrite_output_dir to overcome.""" ) lowerCamelCase__ : Any = import_module("""tasks""" ) try: lowerCamelCase__ : Optional[int] = getattr(UpperCAmelCase__ , model_args.task_type ) lowerCamelCase__ : str = token_classification_task_clazz() except AttributeError: raise ValueError( f'''Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ''' f'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}''' ) # 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.local_rank != -1 ) , training_args.fpaa , ) # 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() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCAmelCase__ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCamelCase__ : List[str] = token_classification_task.get_labels(data_args.labels ) lowerCamelCase__ : Optional[Any] = dict(enumerate(UpperCAmelCase__ ) ) lowerCamelCase__ : Tuple = len(UpperCAmelCase__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase__ : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=UpperCAmelCase__ , idalabel=UpperCAmelCase__ , labelaid={label: i for i, label in enumerate(UpperCAmelCase__ )} , cache_dir=model_args.cache_dir , ) lowerCamelCase__ : Tuple = 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 , use_fast=model_args.use_fast , ) lowerCamelCase__ : List[Any] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCAmelCase__ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCamelCase__ : int = ( TokenClassificationDataset( token_classification_task=UpperCAmelCase__ , data_dir=data_args.data_dir , tokenizer=UpperCAmelCase__ , labels=UpperCAmelCase__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCamelCase__ : Any = ( TokenClassificationDataset( token_classification_task=UpperCAmelCase__ , data_dir=data_args.data_dir , tokenizer=UpperCAmelCase__ , labels=UpperCAmelCase__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(UpperCamelCase , UpperCamelCase ) -> Tuple[List[int], List[int]]: lowerCamelCase__ : Union[str, Any] = np.argmax(UpperCAmelCase__ , axis=2 ) lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = preds.shape lowerCamelCase__ : int = [[] for _ in range(UpperCAmelCase__ )] lowerCamelCase__ : Optional[int] = [[] for _ in range(UpperCAmelCase__ )] for i in range(UpperCAmelCase__ ): for j in range(UpperCAmelCase__ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(UpperCamelCase ) -> Dict: lowerCamelCase__ , lowerCamelCase__ : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(UpperCAmelCase__ , UpperCAmelCase__ ), "precision": precision_score(UpperCAmelCase__ , UpperCAmelCase__ ), "recall": recall_score(UpperCAmelCase__ , UpperCAmelCase__ ), "f1": fa_score(UpperCAmelCase__ , UpperCAmelCase__ ), } # Data collator lowerCamelCase__ : Tuple = DataCollatorWithPadding(UpperCAmelCase__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCamelCase__ : Tuple = Trainer( model=UpperCAmelCase__ , args=UpperCAmelCase__ , train_dataset=UpperCAmelCase__ , eval_dataset=UpperCAmelCase__ , compute_metrics=UpperCAmelCase__ , data_collator=UpperCAmelCase__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCamelCase__ : List[str] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) lowerCamelCase__ : Optional[Any] = trainer.evaluate() lowerCamelCase__ : List[Any] = os.path.join(training_args.output_dir , """eval_results.txt""" ) if trainer.is_world_process_zero(): with open(UpperCAmelCase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" , UpperCAmelCase__ , UpperCAmelCase__ ) writer.write("""%s = %s\n""" % (key, value) ) results.update(UpperCAmelCase__ ) # Predict if training_args.do_predict: lowerCamelCase__ : Dict = TokenClassificationDataset( token_classification_task=UpperCAmelCase__ , data_dir=data_args.data_dir , tokenizer=UpperCAmelCase__ , labels=UpperCAmelCase__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[Any] = trainer.predict(UpperCAmelCase__ ) lowerCamelCase__ , lowerCamelCase__ : Optional[int] = align_predictions(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCamelCase__ : str = os.path.join(training_args.output_dir , """test_results.txt""" ) if trainer.is_world_process_zero(): with open(UpperCAmelCase__ , """w""" ) as writer: for key, value in metrics.items(): logger.info(""" %s = %s""" , UpperCAmelCase__ , UpperCAmelCase__ ) writer.write("""%s = %s\n""" % (key, value) ) # Save predictions lowerCamelCase__ : List[str] = os.path.join(training_args.output_dir , """test_predictions.txt""" ) if trainer.is_world_process_zero(): with open(UpperCAmelCase__ , """w""" ) as writer: with open(os.path.join(data_args.data_dir , """test.txt""" ) , """r""" ) as f: token_classification_task.write_predictions_to_file(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return results def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: main() if __name__ == "__main__": main()
710
'''simple docstring''' import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _lowercase ( _lowercase ): def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCamelCase__ , """width_multiplier""" ) ) class _lowercase : def __init__( self: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: str=13 , UpperCamelCase__: Any=64 , UpperCamelCase__: Optional[Any]=2 , UpperCamelCase__: str=3 , UpperCamelCase__: List[str]="swish" , UpperCamelCase__: Any=3 , UpperCamelCase__: Optional[int]=32 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: int=0.02 , UpperCamelCase__: Dict=True , UpperCamelCase__: Dict=True , UpperCamelCase__: Any=10 , UpperCamelCase__: int=None , UpperCamelCase__: List[Any]=0.25 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Optional[int]=0.0 , ): lowerCamelCase__ : Any = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : str = patch_size lowerCamelCase__ : Optional[int] = num_channels lowerCamelCase__ : Optional[Any] = make_divisible(512 * width_multiplier , divisor=8 ) lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : Any = conv_kernel_size lowerCamelCase__ : Any = output_stride lowerCamelCase__ : Union[str, Any] = classifier_dropout_prob lowerCamelCase__ : List[str] = use_labels lowerCamelCase__ : Optional[Any] = is_training lowerCamelCase__ : List[str] = num_labels lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[Any] = scope lowerCamelCase__ : Tuple = width_multiplier lowerCamelCase__ : List[Any] = ffn_dropout lowerCamelCase__ : Any = attn_dropout def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Tuple = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase__ : str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCamelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCamelCase_ ( self: List[Any] ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Union[str, Any] = MobileViTVaModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : str = model(UpperCamelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : Tuple = self.num_labels lowerCamelCase__ : Dict = MobileViTVaForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : int = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str ): lowerCamelCase__ : List[str] = self.num_labels lowerCamelCase__ : Union[str, Any] = MobileViTVaForSemanticSegmentation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase__ : List[Any] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Any = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) a = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) a = False a = False a = False a = False def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = MobileViTVaModelTester(self ) lowerCamelCase__ : List[str] = MobileViTVaConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def lowerCamelCase_ ( self: Union[str, Any] ): pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Tuple ): pass def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ , lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Tuple = [*signature.parameters.keys()] lowerCamelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): def check_hidden_states_output(UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs.hidden_states lowerCamelCase__ : List[Any] = 5 self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase__ : int = 2 for i in range(len(UpperCamelCase__ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCamelCase__ , lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : int = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__ : str = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Union[str, Any] = MobileViTVaModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> Optional[int]: lowerCamelCase__ : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: Tuple ): return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[Any] = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = self.default_image_processor lowerCamelCase__ : List[Any] = prepare_img() lowerCamelCase__ : Any = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : int = model(**UpperCamelCase__ ) # verify the logits lowerCamelCase__ : str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Any = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Union[str, Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Optional[Any] = model(**UpperCamelCase__ ) lowerCamelCase__ : str = outputs.logits # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCamelCase__ ) lowerCamelCase__ : Any = torch.tensor( [ [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]], [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]], [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]], ] , device=UpperCamelCase__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Optional[Any] = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : List[Any] = model.to(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) lowerCamelCase__ : Optional[Any] = prepare_img() lowerCamelCase__ : Dict = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): lowerCamelCase__ : Dict = model(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = outputs.logits.detach().cpu() lowerCamelCase__ : List[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ , target_sizes=[(50, 60)] ) lowerCamelCase__ : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ ) lowerCamelCase__ : int = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ )
631
0
from __future__ import annotations def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Tuple: if len(_snake_case ) < k or k < 0: raise ValueError("""Invalid Input""" ) lowerCamelCase__ : Dict = sum(array[:k] ) for i in range(len(_snake_case ) - k ): lowerCamelCase__ : Any = current_sum - array[i] + array[i + k] lowerCamelCase__ : int = max(_snake_case , _snake_case ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() _A : List[str] =[randint(-1_000, 1_000) for i in range(100)] _A : int =randint(0, 110) print(F'The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}')
711
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _A : Optional[Any] =logging.get_logger(__name__) _A : Dict ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _A : Tuple ={ '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } _A : List[Any] ={ '''gpt-neox-20b''': 2_048, } class _lowercase ( _lowercase ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["""input_ids""", """attention_mask"""] def __init__( self: Optional[int] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: int=None , UpperCamelCase__: Tuple=None , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Any="<|endoftext|>" , UpperCamelCase__: Union[str, Any]="<|endoftext|>" , UpperCamelCase__: Tuple=False , **UpperCamelCase__: str , ): super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , **UpperCamelCase__ , ) lowerCamelCase__ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: lowerCamelCase__ : Any = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) ) lowerCamelCase__ : Dict = add_prefix_space lowerCamelCase__ : Optional[int] = pre_tok_class(**UpperCamelCase__ ) lowerCamelCase__ : Dict = add_prefix_space def lowerCamelCase_ ( self: int , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): lowerCamelCase__ : Optional[Any] = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: "Conversation" ): lowerCamelCase__ : str = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) + [self.eos_token_id] ) if len(UpperCamelCase__ ) > self.model_max_length: lowerCamelCase__ : int = input_ids[-self.model_max_length :] return input_ids
631
0
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets _A : Dict =datasets.logging.get_logger(__name__) _A : List[str] ='\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n booktitle = {Proceedings of the Fifth Conference on Machine Translation},\n month = {November},\n year = {2020},\n address = {Online},\n publisher = {Association for Computational Linguistics},\n pages = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n title = "{COMET}: A Neural Framework for {MT} Evaluation",\n author = "Rei, Ricardo and\n Stewart, Craig and\n Farinha, Ana C and\n Lavie, Alon",\n booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n month = nov,\n year = "2020",\n address = "Online",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n pages = "2685--2702",\n}\n' _A : List[str] ='\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n' _A : Any ='\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n `scores`: List of scores.\n\nExamples:\n\n >>> comet_metric = datasets.load_metric(\'comet\')\n >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use\n >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n >>> print([round(v, 2) for v in results["scores"]])\n [0.19, 0.92]\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def lowerCamelCase_ ( self: str ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://unbabel.github.io/COMET/html/index.html""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """sources""": datasets.Value("""string""" , id="""sequence""" ), """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/Unbabel/COMET"""] , reference_urls=[ """https://github.com/Unbabel/COMET""", """https://www.aclweb.org/anthology/2020.emnlp-main.213/""", """http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""", ] , ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Any ): if self.config_name == "default": lowerCamelCase__ : Optional[Any] = comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da""" ) ) else: lowerCamelCase__ : List[str] = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Any , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): if gpus is None: lowerCamelCase__ : List[str] = 1 if torch.cuda.is_available() else 0 lowerCamelCase__ : List[Any] = {'''src''': sources, '''mt''': predictions, '''ref''': references} lowerCamelCase__ : Tuple = [dict(zip(UpperCamelCase__ , UpperCamelCase__ ) ) for t in zip(*data.values() )] lowerCamelCase__ : Optional[Any] = self.scorer.predict(UpperCamelCase__ , gpus=UpperCamelCase__ , progress_bar=UpperCamelCase__ ) return {"mean_score": mean_score, "scores": scores}
712
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A : Dict ={ '''configuration_git''': ['''GIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GitConfig''', '''GitVisionConfig'''], '''processing_git''': ['''GitProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : Union[str, Any] =[ '''GIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GitForCausalLM''', '''GitModel''', '''GitPreTrainedModel''', '''GitVisionModel''', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
0
'''simple docstring''' class _lowercase : def __init__( self: Any ): lowerCamelCase__ : Dict = """""" lowerCamelCase__ : Any = """""" lowerCamelCase__ : List[str] = [] def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict ): if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: lowerCamelCase__ : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: lowerCamelCase__ : Optional[Any] = self.__min_dist_top_down_dp(_SCREAMING_SNAKE_CASE , n - 1 ) lowerCamelCase__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , _SCREAMING_SNAKE_CASE ) lowerCamelCase__ : str = self.__min_dist_top_down_dp(m - 1 , n - 1 ) lowerCamelCase__ : int = 1 + min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return self.dp[m][n] def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = worda lowerCamelCase__ : Optional[Any] = worda lowerCamelCase__ : Optional[Any] = [[-1 for _ in range(len(_SCREAMING_SNAKE_CASE ) )] for _ in range(len(_SCREAMING_SNAKE_CASE ) )] return self.__min_dist_top_down_dp(len(_SCREAMING_SNAKE_CASE ) - 1 , len(_SCREAMING_SNAKE_CASE ) - 1 ) def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : int = worda lowerCamelCase__ : Union[str, Any] = worda lowerCamelCase__ : List[str] = len(_SCREAMING_SNAKE_CASE ) lowerCamelCase__ : Optional[Any] = len(_SCREAMING_SNAKE_CASE ) lowerCamelCase__ : List[str] = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty lowerCamelCase__ : Union[str, Any] = j elif j == 0: # second string is empty lowerCamelCase__ : int = i elif worda[i - 1] == worda[j - 1]: # last characters are equal lowerCamelCase__ : Optional[Any] = self.dp[i - 1][j - 1] else: lowerCamelCase__ : List[Any] = self.dp[i][j - 1] lowerCamelCase__ : str = self.dp[i - 1][j] lowerCamelCase__ : Union[str, Any] = self.dp[i - 1][j - 1] lowerCamelCase__ : Union[str, Any] = 1 + min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return self.dp[m][n] if __name__ == "__main__": _A : List[Any] =EditDistance() print('''****************** Testing Edit Distance DP Algorithm ******************''') print() _A : Tuple =input('''Enter the first string: ''').strip() _A : str =input('''Enter the second string: ''').strip() print() print(F'The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}') print(F'The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}') print() print('''*************** End of Testing Edit Distance DP Algorithm ***************''')
713
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin _A : int =get_tests_dir('''fixtures/test_sentencepiece.model''') _A : Tuple ={'''target_lang''': '''fi''', '''source_lang''': '''en'''} _A : int ='''>>zh<<''' _A : Dict ='''Helsinki-NLP/''' if is_torch_available(): _A : List[Any] ='''pt''' elif is_tf_available(): _A : Optional[int] ='''tf''' else: _A : Dict ='''jax''' @require_sentencepiece class _lowercase ( _lowercase , unittest.TestCase ): a = MarianTokenizer a = False a = True def lowerCamelCase_ ( self: List[str] ): super().setUp() lowerCamelCase__ : List[Any] = ["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] lowerCamelCase__ : Optional[Any] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) lowerCamelCase__ : Optional[int] = Path(self.tmpdirname ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) lowerCamelCase__ : Dict = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self: Optional[Any] , **UpperCamelCase__: Any ): return MarianTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] ): return ( "This is a test", "This is a test", ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : Any = """</s>""" lowerCamelCase__ : List[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__ ) , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(UpperCamelCase__ ) , 9 ) def lowerCamelCase_ ( self: int ): self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def lowerCamelCase_ ( self: int ): lowerCamelCase__ : List[Any] = MarianTokenizer.from_pretrained(F'''{ORG_NAME}opus-mt-en-de''' ) lowerCamelCase__ : Optional[int] = en_de_tokenizer(["""I am a small frog"""] , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = [38, 121, 14, 697, 38_848, 0] self.assertListEqual(UpperCamelCase__ , batch.input_ids[0] ) lowerCamelCase__ : List[str] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : Tuple = [x.name for x in Path(UpperCamelCase__ ).glob("""*""" )] self.assertIn("""source.spm""" , UpperCamelCase__ ) MarianTokenizer.from_pretrained(UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : List[Any] = self.get_tokenizer() lowerCamelCase__ : Any = tok( ["""I am a small frog""" * 1_000, """I am a small frog"""] , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Dict = tok(["""I am a tiny frog""", """I am a small frog"""] , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def lowerCamelCase_ ( self: List[str] ): # fmt: off lowerCamelCase__ : int = {"""input_ids""": [[43_495, 462, 20, 42_164, 1_369, 52, 464, 132, 1_703, 492, 13, 7_491, 38_999, 6, 8, 464, 132, 1_703, 492, 13, 4_669, 37_867, 13, 7_525, 27, 1_593, 988, 13, 33_972, 7_029, 6, 20, 8_251, 383, 2, 270, 5_866, 3_788, 2, 2_353, 8_251, 12_338, 2, 13_958, 387, 2, 3_629, 6_953, 188, 2_900, 2, 13_958, 8_011, 11_501, 23, 8_460, 4_073, 34_009, 20, 435, 11_439, 27, 8, 8_460, 4_073, 6_004, 20, 9_988, 375, 27, 33, 266, 1_945, 1_076, 1_350, 37_867, 3_288, 5, 577, 1_076, 4_374, 8, 5_082, 5, 26_453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10_767, 6, 316, 304, 4_239, 3, 0], [148, 15_722, 19, 1_839, 12, 1_350, 13, 22_327, 5_082, 5_418, 47_567, 35_938, 59, 318, 19_552, 108, 2_183, 54, 14_976, 4_835, 32, 547, 1_114, 8, 315, 2_417, 5, 92, 19_088, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100], [36, 6_395, 12_570, 39_147, 11_597, 6, 266, 4, 45_405, 7_296, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase__ , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Union[str, Any] = MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) lowerCamelCase__ : str = """Tämä on testi""" lowerCamelCase__ : Any = """This is a test""" lowerCamelCase__ : int = [76, 7, 2_047, 2] lowerCamelCase__ : List[str] = [69, 12, 11, 940, 2] lowerCamelCase__ : Tuple = tokenizer(UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = tokenizer(text_target=UpperCamelCase__ ).input_ids self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Tuple = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
631
0
'''simple docstring''' import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def SCREAMING_SNAKE_CASE_ () -> Optional[int]: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(UpperCamelCase ): requests.request("""GET""" , """https://huggingface.co""" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("""GET""" , """https://huggingface.co""" , timeout=1.0 ) @pytest.mark.integration def SCREAMING_SNAKE_CASE_ () -> int: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("""GET""" , """https://huggingface.co""" ) def SCREAMING_SNAKE_CASE_ () -> Dict: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(UpperCamelCase ): http_head("""https://huggingface.co""" )
714
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Optional[Any] =logging.get_logger(__name__) _A : Optional[int] ={ '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """rwkv""" a = {"""max_position_embeddings""": """context_length"""} def __init__( self: Tuple , UpperCamelCase__: Optional[Any]=50_277 , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Tuple=4_096 , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Dict=None , UpperCamelCase__: Dict=None , UpperCamelCase__: int=1e-5 , UpperCamelCase__: Any=0 , UpperCamelCase__: str=0 , UpperCamelCase__: Union[str, Any]=6 , UpperCamelCase__: Optional[int]=False , UpperCamelCase__: Dict=True , **UpperCamelCase__: Dict , ): lowerCamelCase__ : Dict = vocab_size lowerCamelCase__ : Optional[Any] = context_length lowerCamelCase__ : Optional[Any] = hidden_size lowerCamelCase__ : Any = num_hidden_layers lowerCamelCase__ : int = attention_hidden_size if attention_hidden_size is not None else hidden_size lowerCamelCase__ : Union[str, Any] = intermediate_size if intermediate_size is not None else 4 * hidden_size lowerCamelCase__ : List[str] = layer_norm_epsilon lowerCamelCase__ : int = rescale_every lowerCamelCase__ : Optional[int] = use_cache lowerCamelCase__ : Dict = bos_token_id lowerCamelCase__ : Any = eos_token_id super().__init__( tie_word_embeddings=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
0
from math import asin, atan, cos, radians, sin, sqrt, tan _A : Optional[Any] =637_8137.0 _A : Union[str, Any] =635_6752.31_4245 _A : Dict =6_378_137 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: lowerCamelCase__ : Optional[int] = (AXIS_A - AXIS_B) / AXIS_A lowerCamelCase__ : List[Any] = atan((1 - flattening) * tan(radians(SCREAMING_SNAKE_CASE_ ) ) ) lowerCamelCase__ : Optional[Any] = atan((1 - flattening) * tan(radians(SCREAMING_SNAKE_CASE_ ) ) ) lowerCamelCase__ : List[str] = radians(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ : List[Any] = radians(SCREAMING_SNAKE_CASE_ ) # Equation lowerCamelCase__ : Tuple = sin((phi_a - phi_a) / 2 ) lowerCamelCase__ : List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda lowerCamelCase__ : Dict = sqrt(sin_sq_phi + (cos(SCREAMING_SNAKE_CASE_ ) * cos(SCREAMING_SNAKE_CASE_ ) * sin_sq_lambda) ) return 2 * RADIUS * asin(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
715
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str =logging.get_logger(__name__) _A : int ={ '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class _lowercase ( _lowercase ): a = """roc_bert""" def __init__( self: Optional[Any] , UpperCamelCase__: Any=30_522 , UpperCamelCase__: Optional[Any]=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: Tuple=12 , UpperCamelCase__: Tuple=3_072 , UpperCamelCase__: str="gelu" , UpperCamelCase__: List[Any]=0.1 , UpperCamelCase__: List[str]=0.1 , UpperCamelCase__: Dict=512 , UpperCamelCase__: str=2 , UpperCamelCase__: str=0.02 , UpperCamelCase__: Tuple=1e-12 , UpperCamelCase__: Any=True , UpperCamelCase__: Union[str, Any]=0 , UpperCamelCase__: List[Any]="absolute" , UpperCamelCase__: Any=None , UpperCamelCase__: Any=True , UpperCamelCase__: Optional[int]=True , UpperCamelCase__: Union[str, Any]=768 , UpperCamelCase__: int=910 , UpperCamelCase__: Tuple=512 , UpperCamelCase__: int=24_858 , UpperCamelCase__: Optional[Any]=True , **UpperCamelCase__: Optional[Any] , ): lowerCamelCase__ : Optional[Any] = vocab_size lowerCamelCase__ : Tuple = max_position_embeddings lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : Tuple = num_attention_heads lowerCamelCase__ : Any = intermediate_size lowerCamelCase__ : List[str] = hidden_act lowerCamelCase__ : str = hidden_dropout_prob lowerCamelCase__ : Dict = attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] = initializer_range lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Optional[Any] = layer_norm_eps lowerCamelCase__ : List[Any] = use_cache lowerCamelCase__ : Tuple = enable_pronunciation lowerCamelCase__ : Union[str, Any] = enable_shape lowerCamelCase__ : Union[str, Any] = pronunciation_embed_dim lowerCamelCase__ : Any = pronunciation_vocab_size lowerCamelCase__ : int = shape_embed_dim lowerCamelCase__ : Tuple = shape_vocab_size lowerCamelCase__ : Optional[Any] = concat_input lowerCamelCase__ : str = position_embedding_type lowerCamelCase__ : Dict = classifier_dropout super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
631
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: return int(input_a == input_a == 0 ) def SCREAMING_SNAKE_CASE_ () -> None: print("""Truth Table of NOR Gate:""" ) print("""| Input 1 | Input 2 | Output |""" ) print(f'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(f'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(f'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(f'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
716
'''simple docstring''' import sys import turtle def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ) -> None: my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) triangle(UpperCamelCase , get_mid(UpperCamelCase , UpperCamelCase ) , get_mid(UpperCamelCase , UpperCamelCase ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( '''Correct format for using this script: ''' '''python fractals.py <int:depth_for_fractal>''' ) _A : Any =turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('''red''') _A : Dict =[(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
631
0
'''simple docstring''' import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Tuple: def wrapper(*UpperCamelCase , **UpperCamelCase ): lowerCamelCase__ : List[str] = timeit.default_timer() lowerCamelCase__ : int = func(*UpperCamelCase , **UpperCamelCase ) lowerCamelCase__ : Tuple = timeit.default_timer() - starttime return delta lowerCamelCase__ : str = func.__name__ return wrapper def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=100 , UpperCamelCase=None ) -> str: lowerCamelCase__ : Any = [] lowerCamelCase__ : int = seq_shapes or {} for i in range(UpperCamelCase ): lowerCamelCase__ : Optional[Any] = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(UpperCamelCase , _ArrayXD ): lowerCamelCase__ : Tuple = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(UpperCamelCase , datasets.Value ): if v.dtype == "string": lowerCamelCase__ : int = """The small grey turtle was surprisingly fast when challenged.""" else: lowerCamelCase__ : List[Any] = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(UpperCamelCase , datasets.Sequence ): while isinstance(UpperCamelCase , datasets.Sequence ): lowerCamelCase__ : str = v.feature lowerCamelCase__ : Any = seq_shapes[k] lowerCamelCase__ : Dict = np.random.rand(*UpperCamelCase ).astype(v.dtype ) lowerCamelCase__ : str = data dummy_data.append((i, example) ) return dummy_data def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase=100 , UpperCamelCase=None ) -> int: lowerCamelCase__ : List[Any] = generate_examples(UpperCamelCase , num_examples=UpperCamelCase , seq_shapes=UpperCamelCase ) with ArrowWriter(features=UpperCamelCase , path=UpperCamelCase ) as writer: for key, record in dummy_data: lowerCamelCase__ : Union[str, Any] = features.encode_example(UpperCamelCase ) writer.write(UpperCamelCase ) lowerCamelCase__ , lowerCamelCase__ : str = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f'''Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.''' ) lowerCamelCase__ : int = datasets.Dataset.from_file(filename=UpperCamelCase , info=datasets.DatasetInfo(features=UpperCamelCase ) ) return dataset
717
'''simple docstring''' from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class _lowercase : def __init__( self: int , UpperCamelCase__: Dict , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Union[str, Any]=7 , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: List[Any]=True , UpperCamelCase__: Optional[Any]=True , UpperCamelCase__: int=True , UpperCamelCase__: List[Any]=99 , UpperCamelCase__: Tuple=32 , UpperCamelCase__: List[str]=2 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Optional[int]=37 , UpperCamelCase__: Any="gelu" , UpperCamelCase__: Any=0.1 , UpperCamelCase__: int=0.1 , UpperCamelCase__: Optional[Any]=512 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Tuple=3 , UpperCamelCase__: Optional[int]=4 , UpperCamelCase__: Union[str, Any]=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Union[str, Any] = 13 lowerCamelCase__ : Any = 7 lowerCamelCase__ : int = True lowerCamelCase__ : Optional[Any] = True lowerCamelCase__ : Dict = True lowerCamelCase__ : List[str] = True lowerCamelCase__ : str = 99 lowerCamelCase__ : Dict = 384 lowerCamelCase__ : Optional[Any] = 2 lowerCamelCase__ : Optional[int] = 4 lowerCamelCase__ : Optional[Any] = 37 lowerCamelCase__ : Union[str, Any] = """gelu""" lowerCamelCase__ : int = 0.1 lowerCamelCase__ : Optional[Any] = 0.1 lowerCamelCase__ : List[Any] = 512 lowerCamelCase__ : Optional[Any] = 16 lowerCamelCase__ : Any = 2 lowerCamelCase__ : Optional[Any] = 0.02 lowerCamelCase__ : int = 3 lowerCamelCase__ : List[str] = 4 lowerCamelCase__ : Any = 128 lowerCamelCase__ : List[Any] = 2 lowerCamelCase__ : Optional[Any] = 9 lowerCamelCase__ : Any = 1 lowerCamelCase__ : Optional[int] = None def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase__ : str = None if self.use_input_mask: lowerCamelCase__ : int = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase__ : List[str] = None if self.use_token_type_ids: lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase__ : int = None lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase__ : Any = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase__ : List[Any] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCamelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: Any ): lowerCamelCase__ : List[Any] = TFConvBertModel(config=UpperCamelCase__ ) lowerCamelCase__ : str = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase__ : List[str] = [input_ids, input_mask] lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: Tuple , UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): lowerCamelCase__ : int = TFConvBertForMaskedLM(config=UpperCamelCase__ ) lowerCamelCase__ : Tuple = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : int = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : int = self.num_labels lowerCamelCase__ : Dict = TFConvBertForSequenceClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: Dict ): lowerCamelCase__ : Optional[int] = self.num_choices lowerCamelCase__ : Dict = TFConvBertForMultipleChoice(config=UpperCamelCase__ ) lowerCamelCase__ : int = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : List[str] = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Any = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase__ : Tuple = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Any , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: int ): lowerCamelCase__ : List[Any] = self.num_labels lowerCamelCase__ : List[str] = TFConvBertForTokenClassification(config=UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase_ ( self: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] ): lowerCamelCase__ : Optional[int] = TFConvBertForQuestionAnswering(config=UpperCamelCase__ ) lowerCamelCase__ : int = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : str = self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : str = config_and_inputs lowerCamelCase__ : Optional[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a = ( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a = False a = False a = False def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Dict = TFConvBertModelTester(self ) lowerCamelCase__ : Dict = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: List[str] ): self.config_tester.run_common_tests() def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ ) @slow def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Dict = True lowerCamelCase__ : Tuple = True if hasattr(UpperCamelCase__ , """use_cache""" ): lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : List[str] = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Tuple = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) for model_class in self.all_model_classes: lowerCamelCase__ : int = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : Dict = len(model(UpperCamelCase__ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ , saved_model=UpperCamelCase__ ) lowerCamelCase__ : int = os.path.join(UpperCamelCase__ , """saved_model""" , """1""" ) lowerCamelCase__ : List[Any] = tf.keras.models.load_model(UpperCamelCase__ ) lowerCamelCase__ : Any = model(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : Dict = outputs["""encoder_hidden_states"""] lowerCamelCase__ : Any = outputs["""encoder_attentions"""] else: lowerCamelCase__ : int = outputs["""hidden_states"""] lowerCamelCase__ : Optional[int] = outputs["""attentions"""] self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def lowerCamelCase_ ( self: int ): lowerCamelCase__ : Union[str, Any] = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) self.assertIsNotNone(UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Union[str, Any] = True lowerCamelCase__ : int = getattr(self.model_tester , """decoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Any = getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) lowerCamelCase__ : Optional[int] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = getattr(self.model_tester , """key_length""" , UpperCamelCase__ ) def check_decoder_attentions_output(UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) self.assertEqual(out_len % 2 , 0 ) lowerCamelCase__ : Any = outputs.decoder_attentions self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(UpperCamelCase__: List[str] ): lowerCamelCase__ : Any = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(UpperCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: lowerCamelCase__ : int = True lowerCamelCase__ : Any = False lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = len(UpperCamelCase__ ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) if self.is_encoder_decoder: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) lowerCamelCase__ : Tuple = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_decoder_attentions_output(UpperCamelCase__ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Dict = model_class(UpperCamelCase__ ) lowerCamelCase__ : Union[str, Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) # Check attention is always last and order is fine lowerCamelCase__ : List[Any] = True lowerCamelCase__ : int = True lowerCamelCase__ : List[Any] = model_class(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = model(self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(UpperCamelCase__ ) ) self.assertEqual(model.config.output_hidden_states , UpperCamelCase__ ) check_encoder_attentions_output(UpperCamelCase__ ) @require_tf class _lowercase ( unittest.TestCase ): @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Dict = TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) lowerCamelCase__ : Optional[Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ )[0] lowerCamelCase__ : Dict = [1, 6, 768] self.assertEqual(output.shape , UpperCamelCase__ ) lowerCamelCase__ : Dict = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCamelCase__ , atol=1e-4 )
631
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: if len(__lowerCAmelCase ) <= 1: return lst lowerCamelCase__ : Optional[int] = 1 while i < len(__lowerCAmelCase ): if lst[i - 1] <= lst[i]: i += 1 else: lowerCamelCase__ : Optional[int] = lst[i], lst[i - 1] i -= 1 if i == 0: lowerCamelCase__ : Any = 1 return lst if __name__ == "__main__": _A : List[str] =input('''Enter numbers separated by a comma:\n''').strip() _A : List[Any] =[int(item) for item in user_input.split(''',''')] print(gnome_sort(unsorted))
718
'''simple docstring''' _A : List[str] ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
631
0
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _A : int =logging.getLogger(__name__) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: return (preds == labels).mean() @dataclass class _lowercase : a = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) a = field( default=__a , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a = field( default=__a , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) a = field( default=__a , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class _lowercase : a = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys() )} ) a = field(metadata={"""help""": """Should contain the data files for the task."""} ) a = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a = field( default=__a , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def SCREAMING_SNAKE_CASE_ () -> List[Any]: lowerCamelCase__ : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[str] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' """ --overwrite_output_dir to overcome.""" ) # 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.local_rank != -1 ) , training_args.fpaa , ) # 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() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , lowercase__ ) # Set seed set_seed(training_args.seed ) try: lowerCamelCase__ : Union[str, Any] = processors[data_args.task_name]() lowerCamelCase__ : Tuple = processor.get_labels() lowerCamelCase__ : int = len(lowercase__ ) except KeyError: raise ValueError("""Task not found: %s""" % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase__ : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowercase__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) lowerCamelCase__ : Optional[int] = 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 , ) lowerCamelCase__ : List[str] = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=lowercase__ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCamelCase__ : Any = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=lowercase__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCamelCase__ : Any = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=lowercase__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(UpperCamelCase ) -> Dict: lowerCamelCase__ : str = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(lowercase__ , p.label_ids )} # Data collator lowerCamelCase__ : Tuple = DataCollatorWithPadding(lowercase__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCamelCase__ : List[Any] = Trainer( model=lowercase__ , args=lowercase__ , train_dataset=lowercase__ , eval_dataset=lowercase__ , compute_metrics=lowercase__ , data_collator=lowercase__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCamelCase__ : Optional[Any] = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) lowerCamelCase__ : str = trainer.evaluate() lowerCamelCase__ : Union[str, Any] = os.path.join(training_args.output_dir , """eval_results.txt""" ) if trainer.is_world_master(): with open(lowercase__ , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(""" %s = %s""" , lowercase__ , lowercase__ ) writer.write("""%s = %s\n""" % (key, value) ) results.update(lowercase__ ) return results def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Any: main() if __name__ == "__main__": main()
719
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Any =logging.get_logger(__name__) _A : Dict ={ '''microsoft/trocr-base-handwritten''': ( '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json''' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class _lowercase ( _lowercase ): a = """trocr""" a = ["""past_key_values"""] a = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Optional[Any] , UpperCamelCase__: int=50_265 , UpperCamelCase__: int=1_024 , UpperCamelCase__: Optional[Any]=12 , UpperCamelCase__: Dict=16 , UpperCamelCase__: int=4_096 , UpperCamelCase__: Tuple="gelu" , UpperCamelCase__: int=512 , UpperCamelCase__: Dict=0.1 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: str=0.0 , UpperCamelCase__: Any=2 , UpperCamelCase__: Dict=0.02 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: str=True , UpperCamelCase__: Tuple=False , UpperCamelCase__: Union[str, Any]=True , UpperCamelCase__: Tuple=True , UpperCamelCase__: Dict=1 , UpperCamelCase__: List[str]=0 , UpperCamelCase__: Union[str, Any]=2 , **UpperCamelCase__: str , ): lowerCamelCase__ : Any = vocab_size lowerCamelCase__ : Tuple = d_model lowerCamelCase__ : Any = decoder_layers lowerCamelCase__ : Dict = decoder_attention_heads lowerCamelCase__ : str = decoder_ffn_dim lowerCamelCase__ : Tuple = activation_function lowerCamelCase__ : Dict = max_position_embeddings lowerCamelCase__ : int = dropout lowerCamelCase__ : int = attention_dropout lowerCamelCase__ : List[Any] = activation_dropout lowerCamelCase__ : Union[str, Any] = init_std lowerCamelCase__ : Optional[int] = decoder_layerdrop lowerCamelCase__ : Dict = use_cache lowerCamelCase__ : Any = scale_embedding lowerCamelCase__ : Optional[int] = use_learned_position_embeddings lowerCamelCase__ : List[str] = layernorm_embedding super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
631
0
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _A : str =logging.get_logger(__name__) _A : Any ={ 'huggingface/time-series-transformer-tourism-monthly': ( 'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json' ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class _lowercase ( __lowercase ): a = '''time_series_transformer''' a = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self: List[str] , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: str = "student_t" , UpperCamelCase__: str = "nll" , UpperCamelCase__: int = 1 , UpperCamelCase__: List[int] = [1, 2, 3, 4, 5, 6, 7] , UpperCamelCase__: Optional[Union[str, bool]] = "mean" , UpperCamelCase__: int = 0 , UpperCamelCase__: int = 0 , UpperCamelCase__: int = 0 , UpperCamelCase__: int = 0 , UpperCamelCase__: Optional[List[int]] = None , UpperCamelCase__: Optional[List[int]] = None , UpperCamelCase__: int = 32 , UpperCamelCase__: int = 32 , UpperCamelCase__: int = 2 , UpperCamelCase__: int = 2 , UpperCamelCase__: int = 2 , UpperCamelCase__: int = 2 , UpperCamelCase__: bool = True , UpperCamelCase__: str = "gelu" , UpperCamelCase__: int = 64 , UpperCamelCase__: float = 0.1 , UpperCamelCase__: float = 0.1 , UpperCamelCase__: float = 0.1 , UpperCamelCase__: float = 0.1 , UpperCamelCase__: float = 0.1 , UpperCamelCase__: int = 100 , UpperCamelCase__: float = 0.02 , UpperCamelCase__: Tuple=True , **UpperCamelCase__: str , ): # time series specific configuration lowerCamelCase__ : str = prediction_length lowerCamelCase__ : Optional[Any] = context_length or prediction_length lowerCamelCase__ : Tuple = distribution_output lowerCamelCase__ : Any = loss lowerCamelCase__ : List[Any] = input_size lowerCamelCase__ : int = num_time_features lowerCamelCase__ : Dict = lags_sequence lowerCamelCase__ : Optional[int] = scaling lowerCamelCase__ : int = num_dynamic_real_features lowerCamelCase__ : Tuple = num_static_real_features lowerCamelCase__ : Any = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) lowerCamelCase__ : int = cardinality else: lowerCamelCase__ : Dict = [0] if embedding_dimension and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) lowerCamelCase__ : str = embedding_dimension else: lowerCamelCase__ : str = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] lowerCamelCase__ : Any = num_parallel_samples # Transformer architecture configuration lowerCamelCase__ : Any = input_size * len(__a ) + self._number_of_features lowerCamelCase__ : List[str] = d_model lowerCamelCase__ : Tuple = encoder_attention_heads lowerCamelCase__ : Optional[int] = decoder_attention_heads lowerCamelCase__ : Union[str, Any] = encoder_ffn_dim lowerCamelCase__ : str = decoder_ffn_dim lowerCamelCase__ : str = encoder_layers lowerCamelCase__ : Any = decoder_layers lowerCamelCase__ : Optional[int] = dropout lowerCamelCase__ : List[str] = attention_dropout lowerCamelCase__ : Tuple = activation_dropout lowerCamelCase__ : Optional[int] = encoder_layerdrop lowerCamelCase__ : int = decoder_layerdrop lowerCamelCase__ : Optional[int] = activation_function lowerCamelCase__ : Optional[Any] = init_std lowerCamelCase__ : Optional[Any] = use_cache super().__init__(is_encoder_decoder=__a , **__a ) @property def lowerCamelCase_ ( self: int ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
720
'''simple docstring''' # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : str = [False] * len(UpperCamelCase ) lowerCamelCase__ : str = [-1] * len(UpperCamelCase ) def dfs(UpperCamelCase , UpperCamelCase ): lowerCamelCase__ : Optional[int] = True lowerCamelCase__ : Union[str, Any] = c for u in graph[v]: if not visited[u]: dfs(UpperCamelCase , 1 - c ) for i in range(len(UpperCamelCase ) ): if not visited[i]: dfs(UpperCamelCase , 0 ) for i in range(len(UpperCamelCase ) ): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph _A : int ={0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
631
0
'''simple docstring''' _A : Any =0 # The first color of the flag. _A : Union[str, Any] =1 # The second color of the flag. _A : List[str] =2 # The third color of the flag. _A : Optional[int] =(red, white, blue) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Dict: if not sequence: return [] if len(_UpperCamelCase ) == 1: return list(_UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = 0 lowerCamelCase__ : Dict = len(_UpperCamelCase ) - 1 lowerCamelCase__ : int = 0 while mid <= high: if sequence[mid] == colors[0]: lowerCamelCase__ , lowerCamelCase__ : Dict = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: lowerCamelCase__ , lowerCamelCase__ : Optional[int] = sequence[high], sequence[mid] high -= 1 else: lowerCamelCase__ : List[str] = f'''The elements inside the sequence must contains only {colors} values''' raise ValueError(_UpperCamelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod() _A : Tuple =input('''Enter numbers separated by commas:\n''').strip() _A : Any =[int(item.strip()) for item in user_input.split(''',''')] print(F'{dutch_national_flag_sort(unsorted)}')
721
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] ): lowerCamelCase__ : Optional[int] = dataset lowerCamelCase__ : Optional[int] = process lowerCamelCase__ : List[str] = params def __len__( self: List[str] ): return len(self.dataset ) def __getitem__( self: Any , UpperCamelCase__: int ): lowerCamelCase__ : Dict = self.dataset[i] lowerCamelCase__ : Union[str, Any] = self.process(UpperCamelCase__ , **self.params ) return processed class _lowercase ( _lowercase ): def __init__( self: Optional[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str , UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): lowerCamelCase__ : int = loader lowerCamelCase__ : str = infer lowerCamelCase__ : Optional[int] = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : int = loader_batch_size # Internal bookkeeping lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : Optional[Any] = None def __len__( self: Dict ): return len(self.loader ) def __iter__( self: Optional[int] ): lowerCamelCase__ : List[Any] = iter(self.loader ) return self def lowerCamelCase_ ( self: Any ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowerCamelCase__ : str = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowerCamelCase__ : int = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Convert ModelOutput to tuple first lowerCamelCase__ : str = element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : Tuple = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCamelCase__ , UpperCamelCase__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowerCamelCase__ : List[str] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowerCamelCase__ : int = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowerCamelCase__ : List[str] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : Optional[Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowerCamelCase__ : int = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowerCamelCase__ : str = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowerCamelCase__ : Optional[int] = self._loader_batch_data.__class__(UpperCamelCase__ ) self._loader_batch_index += 1 return result def lowerCamelCase_ ( self: List[Any] ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowerCamelCase__ : Optional[Any] = next(self.iterator ) lowerCamelCase__ : List[str] = self.infer(UpperCamelCase__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Optional[Any] = processed else: lowerCamelCase__ : Union[str, Any] = list(processed.keys() )[0] lowerCamelCase__ : Any = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : Any = len(UpperCamelCase__ ) else: lowerCamelCase__ : List[str] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : Union[str, Any] = observed_batch_size # Setting internal index to unwrap the batch lowerCamelCase__ : List[Any] = processed lowerCamelCase__ : List[Any] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class _lowercase ( _lowercase ): def __init__( self: List[str] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any]=None ): super().__init__(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __iter__( self: Union[str, Any] ): lowerCamelCase__ : str = iter(self.loader ) lowerCamelCase__ : int = None return self def lowerCamelCase_ ( self: str ): if self.subiterator is None: lowerCamelCase__ : Optional[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowerCamelCase__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowerCamelCase__ : Any = self.infer(next(self.iterator ) , **self.params ) lowerCamelCase__ : Union[str, Any] = next(self.subiterator ) return processed class _lowercase ( _lowercase ): def __iter__( self: List[Any] ): lowerCamelCase__ : int = iter(self.loader ) return self def lowerCamelCase_ ( self: Tuple ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowerCamelCase__ : List[str] = False lowerCamelCase__ : Union[str, Any] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : Any = self.loader_batch_item() lowerCamelCase__ : Tuple = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator while not is_last: lowerCamelCase__ : str = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCamelCase__ , torch.Tensor ): lowerCamelCase__ : Dict = processed else: lowerCamelCase__ : Dict = list(processed.keys() )[0] lowerCamelCase__ : Dict = processed[key] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase__ : List[Any] = len(UpperCamelCase__ ) else: lowerCamelCase__ : Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowerCamelCase__ : str = observed_batch_size lowerCamelCase__ : str = processed lowerCamelCase__ : Optional[int] = 0 while self._loader_batch_index < self.loader_batch_size: lowerCamelCase__ : List[Any] = self.loader_batch_item() lowerCamelCase__ : str = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) if is_last: return accumulator else: lowerCamelCase__ : Optional[Any] = processed lowerCamelCase__ : Optional[int] = item.pop("""is_last""" ) accumulator.append(UpperCamelCase__ ) return accumulator class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str ): lowerCamelCase__ : Union[str, Any] = dataset lowerCamelCase__ : str = key def __len__( self: Optional[Any] ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Any ): return self.dataset[i][self.key] class _lowercase ( _lowercase ): def __init__( self: Optional[int] , UpperCamelCase__: Dataset , UpperCamelCase__: str , UpperCamelCase__: str ): lowerCamelCase__ : str = dataset lowerCamelCase__ : Dict = keya lowerCamelCase__ : List[str] = keya def __len__( self: str ): return len(self.dataset ) def __getitem__( self: List[str] , UpperCamelCase__: Union[str, Any] ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
631
0
'''simple docstring''' import math def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> float: if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("""In Malus Law, the angle is in the range 0-360 degrees""" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(UpperCamelCase ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='''malus_law''')
700
'''simple docstring''' # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys _A : Dict ='''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
631
0
'''simple docstring''' import torch def SCREAMING_SNAKE_CASE_ () -> Dict: if torch.cuda.is_available(): lowerCamelCase__ : List[str] = torch.cuda.device_count() else: lowerCamelCase__ : int = 0 print(f'''Successfully ran on {num_gpus} GPUs''' ) if __name__ == "__main__": main()
701
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _A : Any ={ '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A : str =[ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys _A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
631
0
def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> List[str]: return x if y == 0 else greatest_common_divisor(lowercase__ , x % y ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: return (x * y) // greatest_common_divisor(lowercase__ , lowercase__ ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 20 ) -> Tuple: lowerCamelCase__ : Optional[Any] = 1 for i in range(1 , n + 1 ): lowerCamelCase__ : Optional[Any] = lcm(lowercase__ , lowercase__ ) return g if __name__ == "__main__": print(F'{solution() = }')
702
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : List[str] ={ '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class _lowercase ( _lowercase ): a = """audio-spectrogram-transformer""" def __init__( self: str , UpperCamelCase__: Any=768 , UpperCamelCase__: Union[str, Any]=12 , UpperCamelCase__: List[Any]=12 , UpperCamelCase__: int=3_072 , UpperCamelCase__: Optional[Any]="gelu" , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: Union[str, Any]=0.02 , UpperCamelCase__: Dict=1e-12 , UpperCamelCase__: List[str]=16 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=10 , UpperCamelCase__: List[str]=10 , UpperCamelCase__: Any=1_024 , UpperCamelCase__: Optional[Any]=128 , **UpperCamelCase__: Union[str, Any] , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : List[Any] = hidden_size lowerCamelCase__ : int = num_hidden_layers lowerCamelCase__ : List[str] = num_attention_heads lowerCamelCase__ : Optional[int] = intermediate_size lowerCamelCase__ : List[Any] = hidden_act lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : str = attention_probs_dropout_prob lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : List[str] = layer_norm_eps lowerCamelCase__ : List[Any] = patch_size lowerCamelCase__ : List[str] = qkv_bias lowerCamelCase__ : Dict = frequency_stride lowerCamelCase__ : List[Any] = time_stride lowerCamelCase__ : str = max_length lowerCamelCase__ : Dict = num_mel_bins
631
0
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() _A : Tuple =logging.get_logger(__name__) _A : Dict ='Hello world! cécé herlolip' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> str: lowerCamelCase__ : Optional[Any] = FairseqRobertaModel.from_pretrained(lowerCAmelCase_ ) roberta.eval() # disable dropout lowerCamelCase__ : Optional[int] = roberta.model.encoder.sentence_encoder lowerCamelCase__ : Optional[Any] = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: lowerCamelCase__ : Dict = roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print("""Our RoBERTa config:""" , lowerCAmelCase_ ) lowerCamelCase__ : List[str] = XLMRobertaXLForSequenceClassification(lowerCAmelCase_ ) if classification_head else XLMRobertaXLForMaskedLM(lowerCAmelCase_ ) model.eval() # Now let's copy all the weights. # Embeddings lowerCamelCase__ : int = roberta_sent_encoder.embed_tokens.weight lowerCamelCase__ : Union[str, Any] = roberta_sent_encoder.embed_positions.weight lowerCamelCase__ : str = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. lowerCamelCase__ : List[Any] = roberta_sent_encoder.layer_norm.weight lowerCamelCase__ : List[Any] = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowerCamelCase__ : BertLayer = model.roberta.encoder.layer[i] lowerCamelCase__ : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] lowerCamelCase__ : RobertaAttention = layer.attention lowerCamelCase__ : Optional[Any] = roberta_layer.self_attn_layer_norm.weight lowerCamelCase__ : List[str] = roberta_layer.self_attn_layer_norm.bias # self attention lowerCamelCase__ : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) lowerCamelCase__ : Optional[Any] = roberta_layer.self_attn.q_proj.weight lowerCamelCase__ : int = roberta_layer.self_attn.q_proj.bias lowerCamelCase__ : Optional[int] = roberta_layer.self_attn.k_proj.weight lowerCamelCase__ : Any = roberta_layer.self_attn.k_proj.bias lowerCamelCase__ : List[Any] = roberta_layer.self_attn.v_proj.weight lowerCamelCase__ : Any = roberta_layer.self_attn.v_proj.bias # self-attention output lowerCamelCase__ : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape lowerCamelCase__ : Optional[Any] = roberta_layer.self_attn.out_proj.weight lowerCamelCase__ : Union[str, Any] = roberta_layer.self_attn.out_proj.bias # this one is final layer norm lowerCamelCase__ : str = roberta_layer.final_layer_norm.weight lowerCamelCase__ : Optional[Any] = roberta_layer.final_layer_norm.bias # intermediate lowerCamelCase__ : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape lowerCamelCase__ : str = roberta_layer.fca.weight lowerCamelCase__ : List[Any] = roberta_layer.fca.bias # output lowerCamelCase__ : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape lowerCamelCase__ : Optional[int] = roberta_layer.fca.weight lowerCamelCase__ : Any = roberta_layer.fca.bias # end of layer if classification_head: lowerCamelCase__ : List[Any] = roberta.model.classification_heads['''mnli'''].dense.weight lowerCamelCase__ : Tuple = roberta.model.classification_heads['''mnli'''].dense.bias lowerCamelCase__ : int = roberta.model.classification_heads['''mnli'''].out_proj.weight lowerCamelCase__ : Any = roberta.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head lowerCamelCase__ : Tuple = roberta.model.encoder.lm_head.dense.weight lowerCamelCase__ : Union[str, Any] = roberta.model.encoder.lm_head.dense.bias lowerCamelCase__ : int = roberta.model.encoder.lm_head.layer_norm.weight lowerCamelCase__ : Dict = roberta.model.encoder.lm_head.layer_norm.bias lowerCamelCase__ : int = roberta.model.encoder.lm_head.weight lowerCamelCase__ : Union[str, Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. lowerCamelCase__ : torch.Tensor = roberta.encode(lowerCAmelCase_ ).unsqueeze(0 ) # batch of size 1 lowerCamelCase__ : Any = model(lowerCAmelCase_ )[0] if classification_head: lowerCamelCase__ : Any = roberta.model.classification_heads['''mnli'''](roberta.extract_features(lowerCAmelCase_ ) ) else: lowerCamelCase__ : Any = roberta.model(lowerCAmelCase_ )[0] print(our_output.shape , their_output.shape ) lowerCamelCase__ : str = torch.max(torch.abs(our_output - their_output ) ).item() print(f'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 lowerCamelCase__ : List[Any] = torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1E-3 ) print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" ) if not success: raise Exception("""Something went wRoNg""" ) pathlib.Path(lowerCAmelCase_ ).mkdir(parents=lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _A : Optional[int] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_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.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) _A : Dict =parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
703
'''simple docstring''' import argparse import os import re import packaging.version _A : List[str] ='''examples/''' _A : Any ={ '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''), '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } _A : int ={ '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } _A : int ='''README.md''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> str: with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : List[str] = f.read() lowerCamelCase__ , lowerCamelCase__ : Optional[int] = REPLACE_PATTERNS[pattern] lowerCamelCase__ : Dict = replace.replace("""VERSION""" , UpperCamelCase ) lowerCamelCase__ : str = re_pattern.sub(UpperCamelCase , UpperCamelCase ) with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> str: for folder, directories, fnames in os.walk(UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(UpperCamelCase , UpperCamelCase ) , UpperCamelCase , pattern="""examples""" ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase=False ) -> List[Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if not patch: update_version_in_examples(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: lowerCamelCase__ : Dict = """🤗 Transformers currently provides the following architectures""" lowerCamelCase__ : Dict = """1. Want to contribute a new model?""" with open(UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCamelCase__ : int = f.readlines() # Find the start of the list. lowerCamelCase__ : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowerCamelCase__ : Optional[Any] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): lowerCamelCase__ : List[Any] = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(UpperCamelCase , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ () -> Optional[Any]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: lowerCamelCase__ : int = f.read() lowerCamelCase__ : Optional[Any] = REPLACE_PATTERNS["""init"""][0].search(UpperCamelCase ).groups()[0] return packaging.version.parse(UpperCamelCase ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase=False ) -> List[Any]: lowerCamelCase__ : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: lowerCamelCase__ : List[str] = default_version.base_version elif patch: lowerCamelCase__ : Any = f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowerCamelCase__ : List[Any] = f'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowerCamelCase__ : Any = input(f'''Which version are you releasing? [{default_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Optional[int] = default_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase , patch=UpperCamelCase ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def SCREAMING_SNAKE_CASE_ () -> List[str]: lowerCamelCase__ : Optional[int] = get_version() lowerCamelCase__ : Any = f'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowerCamelCase__ : Any = current_version.base_version # Check with the user we got that right. lowerCamelCase__ : List[Any] = input(f'''Which version are we developing now? [{dev_version}]''' ) if len(UpperCamelCase ) == 0: lowerCamelCase__ : Dict = dev_version print(f'''Updating version to {version}.''' ) global_version_update(UpperCamelCase ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": _A : List[Any] =argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') _A : List[str] =parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
631
0
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Optional[int]: return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: lowerCamelCase__ : Optional[Any] = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue lowerCamelCase__ : Optional[Any] = key.replace("""heads.cmd.mim_head.cls.predictions""" , """mmm_image_head""" ) lowerCamelCase__ : List[Any] = key.replace("""heads.cmd.mlm_head.cls.predictions""" , """mmm_text_head""" ) lowerCamelCase__ : Optional[Any] = key.replace("""heads.cmd.itm_head.cls""" , """itm_head""" ) lowerCamelCase__ : Optional[Any] = key.replace("""heads.cmd.itm_head.pooler""" , """itm_head.pooler""" ) lowerCamelCase__ : Dict = key.replace("""heads.cmd.clip_head.logit_scale""" , """flava.logit_scale""" ) lowerCamelCase__ : List[Any] = key.replace("""heads.fairseq_mlm.cls.predictions""" , """mlm_head""" ) lowerCamelCase__ : Union[str, Any] = key.replace("""heads.imagenet.mim_head.cls.predictions""" , """mim_head""" ) lowerCamelCase__ : Tuple = key.replace("""mm_text_projection""" , """flava.text_to_mm_projection""" ) lowerCamelCase__ : Optional[int] = key.replace("""mm_image_projection""" , """flava.image_to_mm_projection""" ) lowerCamelCase__ : str = key.replace("""image_encoder.module""" , """flava.image_model""" ) lowerCamelCase__ : Optional[Any] = key.replace("""text_encoder.module""" , """flava.text_model""" ) lowerCamelCase__ : List[Any] = key.replace("""mm_encoder.module.encoder.cls_token""" , """flava.multimodal_model.cls_token""" ) lowerCamelCase__ : List[str] = key.replace("""mm_encoder.module""" , """flava.multimodal_model""" ) lowerCamelCase__ : Any = key.replace("""text_projection""" , """flava.text_projection""" ) lowerCamelCase__ : Tuple = key.replace("""image_projection""" , """flava.image_projection""" ) lowerCamelCase__ : Tuple = value.float() for key, value in codebook_state_dict.items(): lowerCamelCase__ : Union[str, Any] = value return upgrade @torch.no_grad() def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=None ) -> Union[str, Any]: if config_path is not None: lowerCamelCase__ : Dict = FlavaConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) else: lowerCamelCase__ : Union[str, Any] = FlavaConfig() lowerCamelCase__ : Optional[Any] = FlavaForPreTraining(SCREAMING_SNAKE_CASE__ ).eval() lowerCamelCase__ : str = convert_dalle_checkpoint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , save_checkpoint=SCREAMING_SNAKE_CASE__ ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): lowerCamelCase__ : str = torch.load(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" ) else: lowerCamelCase__ : str = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" ) lowerCamelCase__ : Tuple = upgrade_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) hf_model.load_state_dict(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Any = hf_model.state_dict() lowerCamelCase__ : Any = count_parameters(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : int = count_parameters(SCREAMING_SNAKE_CASE__ ) + count_parameters(SCREAMING_SNAKE_CASE__ ) assert torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A : Optional[Any] =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 flava checkpoint''') parser.add_argument('''--codebook_path''', default=None, type=str, help='''Path to flava codebook checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') _A : List[str] =parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
704
'''simple docstring''' import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow _A : Union[str, Any] =False class _lowercase ( unittest.TestCase ): def lowerCamelCase_ ( self: Dict , UpperCamelCase__: str=32 ): set_seed(0 ) lowerCamelCase__ : Optional[int] = UNetaDModel(sample_size=UpperCamelCase__ , in_channels=3 , out_channels=3 ) lowerCamelCase__ : List[Any] = torch.optim.SGD(model.parameters() , lr=0.0_001 ) return model, optimizer @slow def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Optional[Any] = """cpu""" # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCamelCase__ : List[Any] = DDPMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) lowerCamelCase__ : Any = DDIMScheduler( num_train_timesteps=1_000 , beta_start=0.0_001 , beta_end=0.02 , beta_schedule="""linear""" , clip_sample=UpperCamelCase__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCamelCase__ : str = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randn((4, 3, 32, 32) ).to(UpperCamelCase__ ) for _ in range(4 )] lowerCamelCase__ : Tuple = [torch.randint(0 , 1_000 , (4,) ).long().to(UpperCamelCase__ ) for _ in range(4 )] # train with a DDPM scheduler lowerCamelCase__ , lowerCamelCase__ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : str = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : str = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Tuple = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(UpperCamelCase__ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase__ : Optional[Any] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase__ : Dict = model(UpperCamelCase__ , timesteps[i] ).sample lowerCamelCase__ : Union[str, Any] = torch.nn.functional.mse_loss(UpperCamelCase__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) ) self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-5 ) )
631
0
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[str]: if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True lowerCamelCase__ : int = 4 lowerCamelCase__ : List[str] = (1 << p) - 1 for _ in range(p - 2 ): lowerCamelCase__ : Union[str, Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
705
'''simple docstring''' from statistics import mean import numpy as np def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : Optional[int] = 0 # Number of processes finished lowerCamelCase__ : Union[str, Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowerCamelCase__ : Tuple = [0] * no_of_process # List to include calculation results lowerCamelCase__ : List[str] = [0] * no_of_process # Sort by arrival time. lowerCamelCase__ : Union[str, Any] = [burst_time[i] for i in np.argsort(UpperCamelCase )] lowerCamelCase__ : List[Any] = [process_name[i] for i in np.argsort(UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: lowerCamelCase__ : str = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowerCamelCase__ : Union[str, Any] = arrival_time[i] lowerCamelCase__ : Any = 0 # Index showing the location of the process being performed lowerCamelCase__ : Union[str, Any] = 0 # Saves the current response ratio. lowerCamelCase__ : Any = 0 for i in range(0 , UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowerCamelCase__ : Optional[int] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowerCamelCase__ : int = temp lowerCamelCase__ : str = i # Calculate the turn around time lowerCamelCase__ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowerCamelCase__ : List[str] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> list: lowerCamelCase__ : int = [0] * no_of_process for i in range(0 , UpperCamelCase ): lowerCamelCase__ : Optional[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _A : List[str] =5 _A : Optional[Any] =['''A''', '''B''', '''C''', '''D''', '''E'''] _A : Optional[int] =[1, 2, 3, 4, 5] _A : Dict =[1, 2, 3, 4, 5] _A : Any =calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _A : Optional[int] =calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('''Process name \tArrival time \tBurst time \tTurn around time \tWaiting time''') for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
631
0
'''simple docstring''' import operator def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase = False , UpperCamelCase = None ) -> Any: lowerCamelCase__ : Optional[int] = operator.lt if reverse else operator.gt lowerCamelCase__ : List[Any] = solution or [] if not arr: return solution lowerCamelCase__ : Union[str, Any] = [arr.pop(0 )] for i, item in enumerate(UpperCamelCase ): if _operator(UpperCamelCase , sublist[-1] ): sublist.append(UpperCamelCase ) arr.pop(UpperCamelCase ) # merging sublist into solution list if not solution: solution.extend(UpperCamelCase ) else: while sublist: lowerCamelCase__ : Tuple = sublist.pop(0 ) for i, xx in enumerate(UpperCamelCase ): if not _operator(UpperCamelCase , UpperCamelCase ): solution.insert(UpperCamelCase , UpperCamelCase ) break else: solution.append(UpperCamelCase ) strand_sort(UpperCamelCase , UpperCamelCase , UpperCamelCase ) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
706
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
631
0
'''simple docstring''' from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
707
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowercase : def __init__( self: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str]=13 , UpperCamelCase__: Optional[int]=30 , UpperCamelCase__: Optional[int]=2 , UpperCamelCase__: List[str]=3 , UpperCamelCase__: List[str]=True , UpperCamelCase__: Any=True , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Any=5 , UpperCamelCase__: Optional[Any]=4 , UpperCamelCase__: Dict=37 , UpperCamelCase__: List[Any]="gelu" , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: Union[str, Any]=0.1 , UpperCamelCase__: List[Any]=10 , UpperCamelCase__: Tuple=0.02 , UpperCamelCase__: Optional[int]=3 , UpperCamelCase__: Dict=0.6 , UpperCamelCase__: int=None , ): lowerCamelCase__ : Dict = parent lowerCamelCase__ : Optional[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Optional[Any] = patch_size lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Any = is_training lowerCamelCase__ : Union[str, Any] = use_labels lowerCamelCase__ : List[str] = hidden_size lowerCamelCase__ : List[str] = num_hidden_layers lowerCamelCase__ : List[Any] = num_attention_heads lowerCamelCase__ : str = intermediate_size lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Any = hidden_dropout_prob lowerCamelCase__ : Optional[int] = attention_probs_dropout_prob lowerCamelCase__ : List[Any] = type_sequence_label_size lowerCamelCase__ : int = initializer_range lowerCamelCase__ : List[str] = mask_ratio lowerCamelCase__ : List[Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) lowerCamelCase__ : str = (image_size // patch_size) ** 2 lowerCamelCase__ : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[int] = None if self.use_labels: lowerCamelCase__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Any = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self: str ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int ): lowerCamelCase__ : Tuple = ViTMAEModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : List[Any] = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self: str , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): lowerCamelCase__ : int = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Optional[int] = model(UpperCamelCase__ ) lowerCamelCase__ : Any = (self.image_size // self.patch_size) ** 2 lowerCamelCase__ : str = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images lowerCamelCase__ : Dict = 1 lowerCamelCase__ : Optional[int] = ViTMAEForPreTraining(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() lowerCamelCase__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = model(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = config_and_inputs lowerCamelCase__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _lowercase ( _lowercase , _lowercase , unittest.TestCase ): a = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () a = {"""feature-extraction""": ViTMAEModel} if is_torch_available() else {} a = False a = False a = False a = False def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Tuple = ViTMAEModelTester(self ) lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 ) def lowerCamelCase_ ( self: Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase_ ( self: Dict ): pass def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : str = model_class(UpperCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCamelCase__ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) ) def lowerCamelCase_ ( self: List[Any] ): lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Any = model_class(UpperCamelCase__ ) lowerCamelCase__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Any = [*signature.parameters.keys()] lowerCamelCase__ : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] ): # make masks reproducible np.random.seed(2 ) lowerCamelCase__ : Tuple = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) lowerCamelCase__ : List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) lowerCamelCase__ : Tuple = torch.from_numpy(UpperCamelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument lowerCamelCase__ : Tuple = pt_noise super().check_pt_tf_models(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Union[str, Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Optional[int] = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) lowerCamelCase__ : Optional[int] = outputs[0].cpu().numpy() lowerCamelCase__ : List[str] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCamelCase__ ) lowerCamelCase__ : List[str] = model_class.from_pretrained(UpperCamelCase__ ) model.to(UpperCamelCase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): lowerCamelCase__ : Tuple = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) # Make sure we don't have nans lowerCamelCase__ : Dict = after_outputs[0].cpu().numpy() lowerCamelCase__ : Tuple = 0 lowerCamelCase__ : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCamelCase__ , 1e-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: int ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: Any ): pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self: List[str] ): pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase_ ( self: Tuple ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCamelCase_ ( self: Optional[int] ): pass @slow def lowerCamelCase_ ( self: List[str] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Tuple = ViTMAEModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE_ () -> List[Any]: lowerCamelCase__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class _lowercase ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self: List[str] ): return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self: Tuple ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) lowerCamelCase__ : str = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(UpperCamelCase__ ) lowerCamelCase__ : Tuple = self.default_image_processor lowerCamelCase__ : List[str] = prepare_img() lowerCamelCase__ : int = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).to(UpperCamelCase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) lowerCamelCase__ : List[str] = ViTMAEConfig() lowerCamelCase__ : int = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) lowerCamelCase__ : Any = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**UpperCamelCase__ , noise=torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ ) ) # verify the logits lowerCamelCase__ : List[str] = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) lowerCamelCase__ : str = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCamelCase__ ) , atol=1e-4 ) )
631
0