code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> list: """simple docstring""" snake_case_ : Tuple = len(_UpperCamelCase ) snake_case_ : Union[str, Any] = [[0] * n for i in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): snake_case_ : Any = y_points[i] for i in range(2 , _UpperCamelCase ): for j in range(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[int] = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
60
import tensorflow as tf from ...tf_utils import shape_list class __lowerCAmelCase ( tf.keras.layers.Layer ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=1 , __magic_name__=False , **__magic_name__ ) -> Dict: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[Any] = vocab_size snake_case_ : Dict = d_embed snake_case_ : Union[str, Any] = d_proj snake_case_ : str = cutoffs + [vocab_size] snake_case_ : int = [0] + self.cutoffs snake_case_ : Optional[int] = div_val snake_case_ : int = self.cutoffs[0] snake_case_ : Any = len(self.cutoffs ) - 1 snake_case_ : Union[str, Any] = self.shortlist_size + self.n_clusters snake_case_ : str = keep_order snake_case_ : int = [] snake_case_ : Union[str, Any] = [] def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' if self.n_clusters > 0: snake_case_ : Tuple = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_weight''' ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_bias''' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: snake_case_ : List[str] = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' , ) self.out_projs.append(__magic_name__ ) else: self.out_projs.append(__magic_name__ ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : List[str] = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] snake_case_ : Optional[Any] = self.d_embed // (self.div_val**i) snake_case_ : int = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' ) self.out_projs.append(__magic_name__ ) snake_case_ : int = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : Any = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) super().build(__magic_name__ ) @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = x if proj is not None: snake_case_ : List[str] = tf.einsum('''ibd,ed->ibe''' , __magic_name__ , __magic_name__ ) return tf.einsum('''ibd,nd->ibn''' , __magic_name__ , __magic_name__ ) + b @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = shape_list(__magic_name__ ) snake_case_ : Tuple = tf.range(lp_size[0] , dtype=target.dtype ) snake_case_ : Dict = tf.stack([r, target] , 1 ) return tf.gather_nd(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=True , __magic_name__=False ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = 0 if self.n_clusters == 0: snake_case_ : Any = self._logit(__magic_name__ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: snake_case_ : Union[str, Any] = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__magic_name__ , logits=__magic_name__ ) snake_case_ : Optional[Any] = tf.nn.log_softmax(__magic_name__ , axis=-1 ) else: snake_case_ : Optional[int] = shape_list(__magic_name__ ) snake_case_ : int = [] snake_case_ : List[Any] = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: snake_case_ : str = (target >= l_idx) & (target < r_idx) snake_case_ : Dict = tf.where(__magic_name__ ) snake_case_ : List[str] = tf.boolean_mask(__magic_name__ , __magic_name__ ) - l_idx if self.div_val == 1: snake_case_ : Any = self.out_layers[0][0][l_idx:r_idx] snake_case_ : Dict = self.out_layers[0][1][l_idx:r_idx] else: snake_case_ : Union[str, Any] = self.out_layers[i][0] snake_case_ : int = self.out_layers[i][1] if i == 0: snake_case_ : List[Any] = tf.concat([cur_W, self.cluster_weight] , 0 ) snake_case_ : Tuple = tf.concat([cur_b, self.cluster_bias] , 0 ) snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[0] ) snake_case_ : Any = tf.nn.log_softmax(__magic_name__ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = self._gather_logprob(__magic_name__ , __magic_name__ ) else: snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[i] ) snake_case_ : Union[str, Any] = tf.nn.log_softmax(__magic_name__ ) snake_case_ : Optional[Any] = self.cutoffs[0] + i - 1 # No probability for the head cluster snake_case_ : Optional[int] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(__magic_name__ ) if target is not None: snake_case_ : Any = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : str = self._gather_logprob(__magic_name__ , __magic_name__ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(__magic_name__ , -cur_logprob , shape_list(__magic_name__ ) ) snake_case_ : str = tf.concat(__magic_name__ , axis=-1 ) if target is not None: if return_mean: snake_case_ : int = tf.reduce_mean(__magic_name__ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(__magic_name__ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(__magic_name__ , name=self.name , aggregation='''mean''' if return_mean else '''''' ) return out
60
1
import numpy # List of input, output pairs lowerCAmelCase_ = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) lowerCAmelCase_ = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) lowerCAmelCase_ = [2, 4, 1, 5] lowerCAmelCase_ = len(train_data) lowerCAmelCase_ = 0.009 def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase="train" ) -> List[str]: """simple docstring""" return calculate_hypothesis_value(_UpperCamelCase , _UpperCamelCase ) - output( _UpperCamelCase , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Optional[int] = 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 lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" 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 lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase=m ) -> Union[str, Any]: """simple docstring""" snake_case_ : Union[str, Any] = 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 lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = summation_of_cost_derivative(_UpperCamelCase , _UpperCamelCase ) / m return cost_derivative_value def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output snake_case_ : Optional[int] = 0.000_002 snake_case_ : List[str] = 0 snake_case_ : List[str] = 0 while True: j += 1 snake_case_ : str = [0, 0, 0, 0] for i in range(0 , len(_UpperCamelCase ) ): snake_case_ : str = get_cost_derivative(i - 1 ) snake_case_ : Any = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _UpperCamelCase , _UpperCamelCase , atol=_UpperCamelCase , rtol=_UpperCamelCase , ): break snake_case_ : Dict = temp_parameter_vector print(('''Number of iterations:''', j) ) def lowerCamelCase_ ( ) -> int: """simple docstring""" 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()
60
import requests def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" snake_case_ : Tuple = {'''Content-Type''': '''application/json'''} snake_case_ : Any = requests.post(_UpperCamelCase , json={'''text''': message_body} , headers=_UpperCamelCase ) if response.status_code != 200: snake_case_ : List[Any] = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_UpperCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('''<YOUR MESSAGE BODY>''', '''<SLACK CHANNEL URL>''')
60
1
import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline lowerCAmelCase_ = argparse.ArgumentParser('''Stable Diffusion script with intel optimization''', add_help=False) parser.add_argument('''--dpm''', action='''store_true''', help='''Enable DPMSolver or not''') parser.add_argument('''--steps''', default=None, type=int, help='''Num inference steps''') lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = '''cpu''' lowerCAmelCase_ = '''a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings''' lowerCAmelCase_ = '''path-to-your-trained-model''' lowerCAmelCase_ = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: lowerCAmelCase_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) lowerCAmelCase_ = pipe.to(device) # to channels last lowerCAmelCase_ = pipe.unet.to(memory_format=torch.channels_last) lowerCAmelCase_ = pipe.vae.to(memory_format=torch.channels_last) lowerCAmelCase_ = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: lowerCAmelCase_ = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex lowerCAmelCase_ = torch.randn(2, 4, 6_4, 6_4) lowerCAmelCase_ = torch.rand(1) * 9_9_9 lowerCAmelCase_ = torch.randn(2, 7_7, 7_6_8) lowerCAmelCase_ = (sample, timestep, encoder_hidden_status) try: lowerCAmelCase_ = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: lowerCAmelCase_ = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) lowerCAmelCase_ = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) lowerCAmelCase_ = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: lowerCAmelCase_ = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute lowerCAmelCase_ = 6_6_6 lowerCAmelCase_ = torch.Generator(device).manual_seed(seed) lowerCAmelCase_ = {'''generator''': generator} if args.steps is not None: lowerCAmelCase_ = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): lowerCAmelCase_ = pipe(prompt, **generate_kwargs).images[0] # save image image.save('''generated.png''')
60
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
1
from manim import * class __lowerCAmelCase ( _a ): def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = Rectangle(height=0.5 , width=0.5 ) snake_case_ : List[str] = Rectangle(height=0.25 , width=0.25 ) snake_case_ : Any = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) snake_case_ : int = [mem.copy() for i in range(6 )] snake_case_ : Dict = [mem.copy() for i in range(6 )] snake_case_ : Optional[Any] = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : Any = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : Optional[Any] = VGroup(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : Optional[int] = Text('''CPU''' , font_size=24 ) snake_case_ : Tuple = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__magic_name__ ) snake_case_ : Union[str, Any] = [mem.copy() for i in range(4 )] snake_case_ : Dict = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : List[Any] = Text('''GPU''' , font_size=24 ) snake_case_ : Dict = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) gpu.move_to([-1, -1, 0] ) self.add(__magic_name__ ) snake_case_ : str = [mem.copy() for i in range(6 )] snake_case_ : Tuple = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : str = Text('''Model''' , font_size=24 ) snake_case_ : Tuple = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) model.move_to([3, -1.0, 0] ) self.add(__magic_name__ ) snake_case_ : List[str] = [] snake_case_ : List[Any] = [] snake_case_ : str = [] for i, rect in enumerate(__magic_name__ ): rect.set_stroke(__magic_name__ ) snake_case_ : Tuple = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__magic_name__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__magic_name__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=__magic_name__ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=__magic_name__ , buff=0.0 ) self.add(__magic_name__ ) model_cpu_arr.append(__magic_name__ ) self.add(*__magic_name__ , *__magic_name__ , *__magic_name__ ) snake_case_ : List[Any] = [mem.copy() for i in range(6 )] snake_case_ : Optional[int] = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : Any = Text('''Loaded Checkpoint''' , font_size=24 ) snake_case_ : List[Any] = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) checkpoint.move_to([3, 0.5, 0] ) self.add(__magic_name__ ) snake_case_ : str = [] snake_case_ : Tuple = [] for i, rect in enumerate(__magic_name__ ): snake_case_ : Optional[int] = fill.copy().set_fill(__magic_name__ , opacity=0.7 ) target.move_to(__magic_name__ ) ckpt_arr.append(__magic_name__ ) snake_case_ : Union[str, Any] = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(__magic_name__ ) self.add(*__magic_name__ , *__magic_name__ ) snake_case_ : Any = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) snake_case_ : Optional[Any] = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__magic_name__ , __magic_name__ ) snake_case_ : List[str] = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(__magic_name__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(__magic_name__ ) snake_case_ : Tuple = MarkupText( F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) snake_case_ : Optional[Any] = [meta_mem.copy() for i in range(6 )] snake_case_ : List[str] = [meta_mem.copy() for i in range(6 )] snake_case_ : Union[str, Any] = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : Optional[Any] = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : List[Any] = VGroup(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0 ) snake_case_ : Dict = Text('''Disk''' , font_size=24 ) snake_case_ : Union[str, Any] = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(__magic_name__ , run_time=3 ) , Write(__magic_name__ , run_time=1 ) , Create(__magic_name__ , run_time=1 ) ) snake_case_ : str = [] for i, rect in enumerate(__magic_name__ ): snake_case_ : Any = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(__magic_name__ , run_time=1.5 ) ) self.play(*__magic_name__ ) self.play(FadeOut(__magic_name__ ) ) snake_case_ : Dict = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(__magic_name__ , run_time=3 ) ) self.play( FadeOut(__magic_name__ , __magic_name__ , *__magic_name__ , *__magic_name__ ) , ) self.wait()
60
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''', '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''', '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''owlvit_text_model''' def __init__(self , __magic_name__=4_9408 , __magic_name__=512 , __magic_name__=2048 , __magic_name__=12 , __magic_name__=8 , __magic_name__=16 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , __magic_name__=0 , __magic_name__=4_9406 , __magic_name__=4_9407 , **__magic_name__ , ) -> str: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : int = vocab_size snake_case_ : str = hidden_size snake_case_ : List[Any] = intermediate_size snake_case_ : str = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : str = hidden_act snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : Union[str, Any] = initializer_range snake_case_ : int = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : str = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit_vision_model''' def __init__(self , __magic_name__=768 , __magic_name__=3072 , __magic_name__=12 , __magic_name__=12 , __magic_name__=3 , __magic_name__=768 , __magic_name__=32 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : Union[str, Any] = intermediate_size snake_case_ : Union[str, Any] = num_hidden_layers snake_case_ : Tuple = num_attention_heads snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = image_size snake_case_ : Dict = patch_size snake_case_ : List[Any] = hidden_act snake_case_ : Tuple = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : List[str] = initializer_range snake_case_ : List[Any] = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : int = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit''' lowerCamelCase_ : Optional[int] = True def __init__(self , __magic_name__=None , __magic_name__=None , __magic_name__=512 , __magic_name__=2.6_592 , __magic_name__=True , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) if text_config is None: snake_case_ : Tuple = {} logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''' ) if vision_config is None: snake_case_ : str = {} logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''' ) snake_case_ : str = OwlViTTextConfig(**__magic_name__ ) snake_case_ : Union[str, Any] = OwlViTVisionConfig(**__magic_name__ ) snake_case_ : Any = projection_dim snake_case_ : Union[str, Any] = logit_scale_init_value snake_case_ : str = return_dict snake_case_ : Any = 1.0 @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = cls.get_config_dict(__magic_name__ , **__magic_name__ ) 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(__magic_name__ , **__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> str: '''simple docstring''' snake_case_ : Optional[int] = {} snake_case_ : Union[str, Any] = text_config snake_case_ : Optional[Any] = vision_config return cls.from_dict(__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = copy.deepcopy(self.__dict__ ) snake_case_ : List[Any] = self.text_config.to_dict() snake_case_ : List[Any] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ] ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''logits_per_image''', {0: '''batch'''}), ('''logits_per_text''', {0: '''batch'''}), ('''text_embeds''', {0: '''batch'''}), ('''image_embeds''', {0: '''batch'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-4 def lowerCamelCase (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Dict = super().generate_dummy_inputs( processor.tokenizer , batch_size=__magic_name__ , seq_length=__magic_name__ , framework=__magic_name__ ) snake_case_ : List[str] = super().generate_dummy_inputs( processor.image_processor , batch_size=__magic_name__ , framework=__magic_name__ ) return {**text_input_dict, **image_input_dict} @property def lowerCamelCase (self ) -> int: '''simple docstring''' return 14
60
1
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = GPTSwaTokenizer lowerCamelCase_ : List[str] = False lowerCamelCase_ : List[str] = True lowerCamelCase_ : Union[str, Any] = False def lowerCamelCase (self ) -> Dict: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ : List[Any] = GPTSwaTokenizer(__magic_name__ , eos_token='''<unk>''' , bos_token='''<unk>''' , pad_token='''<unk>''' ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , __magic_name__ ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = '''This is a test''' snake_case_ : Tuple = '''This is a test''' return input_text, output_text def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : int = '''<s>''' snake_case_ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(__magic_name__ ) , 2000 ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = GPTSwaTokenizer(__magic_name__ ) snake_case_ : Optional[int] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__magic_name__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , [465, 287, 265, 631, 842] ) snake_case_ : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) # fmt: off self.assertListEqual( __magic_name__ , ['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.'''] , ) # fmt: on snake_case_ : Union[str, Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual( __magic_name__ , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) snake_case_ : Union[str, Any] = tokenizer.convert_ids_to_tokens(__magic_name__ ) # fmt: off self.assertListEqual( __magic_name__ , ['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.'''] ) # fmt: on def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = GPTSwaTokenizer(__magic_name__ ) snake_case_ : Tuple = ['''This is a test''', '''I was born in 92000, and this is falsé.'''] snake_case_ : str = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(__magic_name__ , __magic_name__ ): self.assertListEqual(tokenizer.encode_fast(__magic_name__ ) , __magic_name__ ) # Test that decode_fast returns the input text for text, token_ids in zip(__magic_name__ , __magic_name__ ): self.assertEqual(tokenizer.decode_fast(__magic_name__ ) , __magic_name__ ) @slow def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : int = [ '''<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')''', '''Hey there, how are you doing this fine day?''', '''This is a text with a trailing spaces followed by a dot .''', '''Häj sväjs lillebrör! =)''', '''Det är inget fel på Mr. Cool''', ] # fmt: off snake_case_ : Optional[Any] = {'''input_ids''': [[6_3423, 5, 6811, 1_4954, 282, 816, 3821, 6_3466, 6_3425, 6_3462, 18, 6_3978, 678, 301, 1320, 6_3423, 6_3455, 6_3458, 18, 6_3982, 4246, 3940, 1901, 4_7789, 5547, 1_8994], [1_9630, 1100, 6_3446, 1342, 633, 544, 4488, 593, 5102, 2416, 6_3495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 5_8593, 2_2413, 9106, 546, 268, 3_3213, 6_3979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5130, 6_3450, 924, 6_3449, 2249, 4062, 1558, 318, 6_3504, 2_1498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 6_3443, 2_6801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''AI-Sweden/gpt-sw3-126m''' , sequences=__magic_name__ , )
60
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) lowerCamelCase_ : Union[str, Any] = ['''accelerate''', '''launch'''] lowerCamelCase_ : Tuple = Path.home() / '''.cache/huggingface/accelerate''' lowerCamelCase_ : Tuple = '''default_config.yaml''' lowerCamelCase_ : str = config_folder / config_file lowerCamelCase_ : List[Any] = config_folder / '''_default_config.yaml''' lowerCamelCase_ : Dict = Path('''tests/test_configs''' ) @classmethod def lowerCamelCase (cls ) -> Dict: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCamelCase (cls ) -> Any: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=__magic_name__ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(__magic_name__ ), self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''test-tpu''' lowerCamelCase_ : Dict = '''us-central1-a''' lowerCamelCase_ : Any = '''ls''' lowerCamelCase_ : Dict = ['''accelerate''', '''tpu-config'''] lowerCamelCase_ : Tuple = '''cd /usr/share''' lowerCamelCase_ : List[Any] = '''tests/test_samples/test_command_file.sh''' lowerCamelCase_ : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : int = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=__magic_name__ ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , )
60
1
import requests def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" snake_case_ : Tuple = {'''Content-Type''': '''application/json'''} snake_case_ : Any = requests.post(_UpperCamelCase , json={'''text''': message_body} , headers=_UpperCamelCase ) if response.status_code != 200: snake_case_ : List[Any] = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_UpperCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('''<YOUR MESSAGE BODY>''', '''<SLACK CHANNEL URL>''')
60
import warnings from ..trainer import Trainer from ..utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__=None , **__magic_name__ ) -> Dict: '''simple docstring''' warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , __magic_name__ , ) super().__init__(args=__magic_name__ , **__magic_name__ )
60
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_instructblip''': [ '''INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InstructBlipConfig''', '''InstructBlipQFormerConfig''', '''InstructBlipVisionConfig''', ], '''processing_instructblip''': ['''InstructBlipProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InstructBlipQFormerModel''', '''InstructBlipPreTrainedModel''', '''InstructBlipForConditionalGeneration''', '''InstructBlipVisionModel''', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" snake_case_ : str = '''mock-s3-bucket''' snake_case_ : str = f'''s3://{mock_bucket}''' snake_case_ : Any = extract_path_from_uri(_UpperCamelCase ) assert dataset_path.startswith('''s3://''' ) is False snake_case_ : Optional[Any] = '''./local/path''' snake_case_ : List[str] = extract_path_from_uri(_UpperCamelCase ) assert dataset_path == new_dataset_path def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : Union[str, Any] = is_remote_filesystem(_UpperCamelCase ) assert is_remote is True snake_case_ : Union[str, Any] = fsspec.filesystem('''file''' ) snake_case_ : int = is_remote_filesystem(_UpperCamelCase ) assert is_remote is False @pytest.mark.parametrize('''compression_fs_class''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : Optional[Any] = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file} snake_case_ : Optional[Any] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case_ : List[Any] = f'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_UpperCamelCase ) snake_case_ : Dict = fsspec.filesystem(compression_fs_class.protocol , fo=_UpperCamelCase ) assert isinstance(_UpperCamelCase , _UpperCamelCase ) snake_case_ : int = os.path.basename(_UpperCamelCase ) snake_case_ : Any = expected_filename[: expected_filename.rindex('''.''' )] assert fs.glob('''*''' ) == [expected_filename] with fs.open(_UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f, open(_UpperCamelCase , encoding='''utf-8''' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('''protocol''' , ['''zip''', '''gzip'''] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Union[str, Any] = {'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path} snake_case_ : Any = compressed_file_paths[protocol] snake_case_ : Any = '''dataset.jsonl''' snake_case_ : Dict = f'''{protocol}://{member_file_path}::{compressed_file_path}''' snake_case_ , *snake_case_ : Optional[Any] = fsspec.get_fs_token_paths(_UpperCamelCase ) assert fs.isfile(_UpperCamelCase ) assert not fs.isfile('''non_existing_''' + member_file_path ) @pytest.mark.integration def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : Optional[int] = hf_api.dataset_info(_UpperCamelCase , token=_UpperCamelCase ) snake_case_ : List[str] = HfFileSystem(repo_info=_UpperCamelCase , token=_UpperCamelCase ) assert sorted(hffs.glob('''*''' ) ) == [".gitattributes", "data"] assert hffs.isdir('''data''' ) assert hffs.isfile('''.gitattributes''' ) and hffs.isfile('''data/text_data.txt''' ) with open(_UpperCamelCase ) as f: assert hffs.open('''data/text_data.txt''' , '''r''' ).read() == f.read() def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Tuple = '''bz2''' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_UpperCamelCase , _UpperCamelCase , clobber=_UpperCamelCase ) with pytest.warns(_UpperCamelCase ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_UpperCamelCase ) == 1 assert ( str(warning_info[0].message ) == f'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
60
1
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" return round(float(moles / volume ) * nfactor ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" return round(float((moles * 0.0_821 * temperature) / (volume) ) ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" return round(float((moles * 0.0_821 * temperature) / (pressure) ) ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" return round(float((pressure * volume) / (0.0_821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
60
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[Any] = '''encoder-decoder''' lowerCamelCase_ : Optional[Any] = True def __init__(self , **__magic_name__ ) -> Optional[int]: '''simple docstring''' super().__init__(**__magic_name__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" snake_case_ : Any = kwargs.pop('''encoder''' ) snake_case_ : Tuple = encoder_config.pop('''model_type''' ) snake_case_ : Union[str, Any] = kwargs.pop('''decoder''' ) snake_case_ : Union[str, Any] = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig snake_case_ : Optional[int] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : List[str] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : Any = True @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> PretrainedConfig: '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) snake_case_ : Tuple = True snake_case_ : Optional[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = copy.deepcopy(self.__dict__ ) snake_case_ : Any = self.encoder.to_dict() snake_case_ : Dict = self.decoder.to_dict() snake_case_ : Union[str, Any] = self.__class__.model_type return output
60
1
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = (DDIMParallelScheduler,) lowerCamelCase_ : Tuple = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def lowerCamelCase (self , **__magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : List[str] = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**__magic_name__ ) return config def lowerCamelCase (self , **__magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.scheduler_classes[0] snake_case_ : Tuple = self.get_scheduler_config(**__magic_name__ ) snake_case_ : List[Any] = scheduler_class(**__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = 10, 0.0 snake_case_ : Union[str, Any] = self.dummy_model() snake_case_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(__magic_name__ ) for t in scheduler.timesteps: snake_case_ : Optional[int] = model(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ).prev_sample return sample def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__magic_name__ ) snake_case_ : int = self.scheduler_classes[0] snake_case_ : List[str] = self.get_scheduler_config(steps_offset=1 ) snake_case_ : Optional[int] = scheduler_class(**__magic_name__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__magic_name__ , beta_end=__magic_name__ ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__magic_name__ ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__magic_name__ ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' self.check_over_configs(thresholding=__magic_name__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__magic_name__ , prediction_type=__magic_name__ , sample_max_value=__magic_name__ , ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for t in [1, 10, 49]: self.check_over_forward(time_step=__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__magic_name__ , num_inference_steps=__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__magic_name__ , eta=__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.scheduler_classes[0] snake_case_ : List[Any] = self.get_scheduler_config() snake_case_ : Optional[Any] = scheduler_class(**__magic_name__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Any = self.scheduler_classes[0] snake_case_ : int = self.get_scheduler_config() snake_case_ : List[str] = scheduler_class(**__magic_name__ ) snake_case_ , snake_case_ : Any = 10, 0.0 scheduler.set_timesteps(__magic_name__ ) snake_case_ : List[Any] = self.dummy_model() snake_case_ : Tuple = self.dummy_sample_deter snake_case_ : Optional[Any] = self.dummy_sample_deter + 0.1 snake_case_ : Optional[Any] = self.dummy_sample_deter - 0.1 snake_case_ : str = samplea.shape[0] snake_case_ : Any = torch.stack([samplea, samplea, samplea] , dim=0 ) snake_case_ : Any = torch.arange(__magic_name__ )[0:3, None].repeat(1 , __magic_name__ ) snake_case_ : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) snake_case_ : List[Any] = scheduler.batch_step_no_noise(__magic_name__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __magic_name__ ) snake_case_ : str = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : Optional[int] = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Any = self.full_loop() snake_case_ : Optional[Any] = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : Tuple = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[Any] = self.full_loop(prediction_type='''v_prediction''' ) snake_case_ : Optional[int] = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : List[str] = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.full_loop(set_alpha_to_one=__magic_name__ , beta_start=0.01 ) snake_case_ : Optional[Any] = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : Dict = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = self.full_loop(set_alpha_to_one=__magic_name__ , beta_start=0.01 ) snake_case_ : int = torch.sum(torch.abs(__magic_name__ ) ) snake_case_ : List[str] = torch.mean(torch.abs(__magic_name__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
60
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[int] = question_encoder snake_case_ : Optional[int] = generator snake_case_ : Optional[Any] = self.question_encoder def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' if os.path.isfile(__magic_name__ ): raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) snake_case_ : str = os.path.join(__magic_name__ , '''question_encoder_tokenizer''' ) snake_case_ : List[Any] = os.path.join(__magic_name__ , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(__magic_name__ ) self.generator.save_pretrained(__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> Any: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case_ : List[str] = kwargs.pop('''config''' , __magic_name__ ) if config is None: snake_case_ : int = RagConfig.from_pretrained(__magic_name__ ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=__magic_name__ , generator=__magic_name__ ) def __call__(self , *__magic_name__ , **__magic_name__ ) -> Tuple: '''simple docstring''' return self.current_tokenizer(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' return self.generator.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' return self.generator.decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.question_encoder def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.generator def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "longest" , __magic_name__ = None , __magic_name__ = True , **__magic_name__ , ) -> BatchEncoding: '''simple docstring''' warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , __magic_name__ , ) if max_length is None: snake_case_ : Dict = self.current_tokenizer.model_max_length snake_case_ : List[str] = self( __magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , max_length=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case_ : Optional[int] = self.current_tokenizer.model_max_length snake_case_ : Union[str, Any] = self( text_target=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , padding=__magic_name__ , max_length=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) snake_case_ : str = labels['''input_ids'''] return model_inputs
60
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : int = CycleDiffusionPipeline lowerCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } lowerCamelCase_ : Union[str, Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} lowerCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} ) lowerCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase_ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case_ : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) snake_case_ : Dict = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , num_train_timesteps=1000 , clip_sample=__magic_name__ , set_alpha_to_one=__magic_name__ , ) torch.manual_seed(0 ) snake_case_ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case_ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) snake_case_ : Optional[Any] = CLIPTextModel(__magic_name__ ) snake_case_ : Union[str, Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) snake_case_ : Tuple = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def lowerCamelCase (self , __magic_name__ , __magic_name__=0 ) -> Dict: '''simple docstring''' snake_case_ : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) snake_case_ : Union[str, Any] = image / 2 + 0.5 if str(__magic_name__ ).startswith('''mps''' ): snake_case_ : int = torch.manual_seed(__magic_name__ ) else: snake_case_ : Optional[int] = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) snake_case_ : List[str] = { '''prompt''': '''An astronaut riding an elephant''', '''source_prompt''': '''An astronaut riding a horse''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''eta''': 0.1, '''strength''': 0.8, '''guidance_scale''': 3, '''source_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case_ : str = self.get_dummy_components() snake_case_ : Union[str, Any] = CycleDiffusionPipeline(**__magic_name__ ) snake_case_ : Optional[Any] = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) snake_case_ : Optional[Any] = self.get_dummy_inputs(__magic_name__ ) snake_case_ : int = pipe(**__magic_name__ ) snake_case_ : Dict = output.images snake_case_ : Tuple = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) snake_case_ : List[str] = np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = self.get_dummy_components() for name, module in components.items(): if hasattr(__magic_name__ , '''half''' ): snake_case_ : Optional[int] = module.half() snake_case_ : str = CycleDiffusionPipeline(**__magic_name__ ) snake_case_ : Any = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) snake_case_ : List[str] = self.get_dummy_inputs(__magic_name__ ) snake_case_ : int = pipe(**__magic_name__ ) snake_case_ : Union[str, Any] = output.images snake_case_ : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) snake_case_ : Optional[int] = np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCamelCase (self ) -> str: '''simple docstring''' return super().test_save_load_local() @unittest.skip('''non-deterministic pipeline''' ) def lowerCamelCase (self ) -> str: '''simple docstring''' return super().test_inference_batch_single_identical() @skip_mps def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' return super().test_dict_tuple_outputs_equivalent() @skip_mps def lowerCamelCase (self ) -> int: '''simple docstring''' return super().test_save_load_optional_components() @skip_mps def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) snake_case_ : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy''' ) snake_case_ : Dict = init_image.resize((512, 512) ) snake_case_ : Optional[int] = '''CompVis/stable-diffusion-v1-4''' snake_case_ : List[str] = DDIMScheduler.from_pretrained(__magic_name__ , subfolder='''scheduler''' ) snake_case_ : Optional[int] = CycleDiffusionPipeline.from_pretrained( __magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , torch_dtype=torch.floataa , revision='''fp16''' ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() snake_case_ : List[Any] = '''A black colored car''' snake_case_ : int = '''A blue colored car''' snake_case_ : int = torch.manual_seed(0 ) snake_case_ : List[Any] = pipe( prompt=__magic_name__ , source_prompt=__magic_name__ , image=__magic_name__ , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__magic_name__ , output_type='''np''' , ) snake_case_ : List[Any] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) snake_case_ : str = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy''' ) snake_case_ : Union[str, Any] = init_image.resize((512, 512) ) snake_case_ : Optional[int] = '''CompVis/stable-diffusion-v1-4''' snake_case_ : Optional[int] = DDIMScheduler.from_pretrained(__magic_name__ , subfolder='''scheduler''' ) snake_case_ : int = CycleDiffusionPipeline.from_pretrained(__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) pipe.enable_attention_slicing() snake_case_ : Any = '''A black colored car''' snake_case_ : List[Any] = '''A blue colored car''' snake_case_ : Any = torch.manual_seed(0 ) snake_case_ : Optional[Any] = pipe( prompt=__magic_name__ , source_prompt=__magic_name__ , image=__magic_name__ , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__magic_name__ , output_type='''np''' , ) snake_case_ : Dict = output.images assert np.abs(image - expected_image ).max() < 2e-2
60
import inspect import unittest from transformers import ViTMSNConfig 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 ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=30 , __magic_name__=2 , __magic_name__=3 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.02 , __magic_name__=None , ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : List[Any] = image_size snake_case_ : Optional[int] = patch_size snake_case_ : Optional[Any] = num_channels snake_case_ : Optional[Any] = is_training snake_case_ : List[Any] = use_labels snake_case_ : Optional[int] = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = intermediate_size snake_case_ : Any = hidden_act snake_case_ : List[str] = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : List[str] = type_sequence_label_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ : Any = (image_size // patch_size) ** 2 snake_case_ : int = num_patches + 1 def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : List[Any] = None if self.use_labels: snake_case_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : int = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = ViTMSNModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[str] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = self.type_sequence_label_size snake_case_ : Tuple = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Any = model(__magic_name__ , labels=__magic_name__ ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ : Optional[int] = 1 snake_case_ : List[str] = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ : Any = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ : Optional[int] = config_and_inputs snake_case_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () lowerCamelCase_ : Optional[int] = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[Any] = ViTMSNModelTester(self ) snake_case_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Any = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , nn.Linear ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Tuple = model_class(__magic_name__ ) snake_case_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : Optional[int] = [*signature.parameters.keys()] snake_case_ : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : str = ViTMSNModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' torch.manual_seed(2 ) snake_case_ : List[str] = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__magic_name__ ) snake_case_ : str = self.default_image_processor snake_case_ : str = prepare_img() snake_case_ : int = image_processor(images=__magic_name__ , return_tensors='''pt''' ).to(__magic_name__ ) # forward pass with torch.no_grad(): snake_case_ : Optional[int] = model(**__magic_name__ ) # verify the logits snake_case_ : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) snake_case_ : List[Any] = torch.tensor([-0.0_803, -0.4_454, -0.2_375] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1e-4 ) )
60
1
def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : str = '''''' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def lowerCamelCase_ ( _UpperCamelCase ) -> dict[str, str]: """simple docstring""" snake_case_ : Tuple = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key snake_case_ : Optional[Any] = remove_duplicates(key.upper() ) snake_case_ : str = len(_UpperCamelCase ) # First fill cipher with key characters snake_case_ : Any = {alphabet[i]: char for i, char in enumerate(_UpperCamelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_UpperCamelCase ) , 26 ): snake_case_ : str = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 snake_case_ : Union[str, Any] = alphabet[i - offset] snake_case_ : Optional[Any] = char return cipher_alphabet def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" return "".join(cipher_map.get(_UpperCamelCase , _UpperCamelCase ) for ch in message.upper() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : List[Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_UpperCamelCase , _UpperCamelCase ) for ch in message.upper() ) def lowerCamelCase_ ( ) -> None: """simple docstring""" snake_case_ : str = input('''Enter message to encode or decode: ''' ).strip() snake_case_ : int = input('''Enter keyword: ''' ).strip() snake_case_ : Optional[Any] = input('''Encipher or decipher? E/D:''' ).strip()[0].lower() try: snake_case_ : Optional[int] = {'''e''': encipher, '''d''': decipher}[option] except KeyError: raise KeyError('''invalid input option''' ) snake_case_ : Optional[int] = create_cipher_map(_UpperCamelCase ) print(func(_UpperCamelCase , _UpperCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = '''efficientnet''' def __init__(self , __magic_name__ = 3 , __magic_name__ = 600 , __magic_name__ = 2.0 , __magic_name__ = 3.1 , __magic_name__ = 8 , __magic_name__ = [3, 3, 5, 3, 5, 5, 3] , __magic_name__ = [32, 16, 24, 40, 80, 112, 192] , __magic_name__ = [16, 24, 40, 80, 112, 192, 320] , __magic_name__ = [] , __magic_name__ = [1, 2, 2, 2, 1, 2, 1] , __magic_name__ = [1, 2, 2, 3, 3, 4, 1] , __magic_name__ = [1, 6, 6, 6, 6, 6, 6] , __magic_name__ = 0.25 , __magic_name__ = "swish" , __magic_name__ = 2560 , __magic_name__ = "mean" , __magic_name__ = 0.02 , __magic_name__ = 0.001 , __magic_name__ = 0.99 , __magic_name__ = 0.5 , __magic_name__ = 0.2 , **__magic_name__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[str] = num_channels snake_case_ : Tuple = image_size snake_case_ : Union[str, Any] = width_coefficient snake_case_ : Tuple = depth_coefficient snake_case_ : Optional[Any] = depth_divisor snake_case_ : Optional[int] = kernel_sizes snake_case_ : str = in_channels snake_case_ : Optional[Any] = out_channels snake_case_ : int = depthwise_padding snake_case_ : Optional[Any] = strides snake_case_ : Any = num_block_repeats snake_case_ : Optional[Any] = expand_ratios snake_case_ : Union[str, Any] = squeeze_expansion_ratio snake_case_ : Union[str, Any] = hidden_act snake_case_ : Union[str, Any] = hidden_dim snake_case_ : Any = pooling_type snake_case_ : List[str] = initializer_range snake_case_ : str = batch_norm_eps snake_case_ : Optional[int] = batch_norm_momentum snake_case_ : Optional[Any] = dropout_rate snake_case_ : List[str] = drop_connect_rate snake_case_ : Union[str, Any] = sum(__magic_name__ ) * 4 class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = version.parse('''1.11''' ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-5
60
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_upernet''': ['''UperNetConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''UperNetForSemanticSegmentation''', '''UperNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) lowerCAmelCase_ = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser( description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)''' ) parser.add_argument( '''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.''' ) parser.add_argument( '''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.''' ) parser.add_argument('''--vocab_size''', default=3_0_5_2_2, type=int) lowerCAmelCase_ = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, '''rb''') as fp: lowerCAmelCase_ = pickle.load(fp) logger.info('''Counting occurrences for MLM.''') lowerCAmelCase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase_ = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase_ = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, '''wb''') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
60
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=10 , __magic_name__=3 , __magic_name__=2 , __magic_name__=2 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.02 , __magic_name__="divided_space_time" , __magic_name__=None , ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : Optional[Any] = batch_size snake_case_ : Union[str, Any] = image_size snake_case_ : Tuple = num_channels snake_case_ : int = patch_size snake_case_ : str = num_frames snake_case_ : str = is_training snake_case_ : Dict = use_labels snake_case_ : Optional[int] = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : List[str] = num_attention_heads snake_case_ : Union[str, Any] = intermediate_size snake_case_ : int = hidden_act snake_case_ : int = hidden_dropout_prob snake_case_ : Any = attention_probs_dropout_prob snake_case_ : Tuple = attention_type snake_case_ : Any = initializer_range snake_case_ : Optional[int] = scope snake_case_ : List[str] = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token snake_case_ : Any = (image_size // patch_size) ** 2 snake_case_ : List[str] = (num_frames) * self.num_patches_per_frame + 1 def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[int] = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) snake_case_ : List[str] = None if self.use_labels: snake_case_ : Dict = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ : List[Any] = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : int = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) snake_case_ : Tuple = self.num_labels return config def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[int]: '''simple docstring''' snake_case_ : Dict = TimesformerModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[str] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[int] = TimesformerForVideoClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Union[str, Any] = model(__magic_name__ ) # verify the logits shape snake_case_ : Tuple = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ : Union[str, Any] = config_and_inputs snake_case_ : str = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () lowerCamelCase_ : Union[str, Any] = ( {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification} if is_torch_available() else {} ) lowerCamelCase_ : List[str] = False lowerCamelCase_ : List[Any] = False lowerCamelCase_ : Dict = False lowerCamelCase_ : List[Any] = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = TimesformerModelTester(self ) snake_case_ : Tuple = ConfigTester( self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=False ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = copy.deepcopy(__magic_name__ ) if return_labels: if model_class in get_values(__magic_name__ ): snake_case_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__magic_name__ ) return inputs_dict def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' pass def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ , snake_case_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Tuple = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , nn.Linear ) ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Optional[int] = model_class(__magic_name__ ) snake_case_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : List[str] = [*signature.parameters.keys()] snake_case_ : str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__magic_name__ ) @slow def lowerCamelCase (self ) -> int: '''simple docstring''' for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : Optional[Any] = TimesformerModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' if not self.has_attentions: pass else: snake_case_ , snake_case_ : int = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ : Union[str, Any] = True for model_class in self.all_model_classes: snake_case_ : List[Any] = self.model_tester.seq_length snake_case_ : List[Any] = self.model_tester.num_frames snake_case_ : List[str] = True snake_case_ : Union[str, Any] = False snake_case_ : List[str] = True snake_case_ : List[Any] = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): snake_case_ : Optional[Any] = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) snake_case_ : Optional[Any] = outputs.attentions self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case_ : Dict = True snake_case_ : Optional[int] = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): snake_case_ : Tuple = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) snake_case_ : List[Any] = outputs.attentions self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) snake_case_ : Dict = len(__magic_name__ ) # Check attention is always last and order is fine snake_case_ : Dict = True snake_case_ : Any = True snake_case_ : int = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): snake_case_ : Dict = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) self.assertEqual(out_len + 1 , len(__magic_name__ ) ) snake_case_ : Optional[Any] = outputs.attentions self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def lowerCamelCase (self ) -> str: '''simple docstring''' def check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ): snake_case_ : List[Any] = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): snake_case_ : List[Any] = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) snake_case_ : str = outputs.hidden_states snake_case_ : List[Any] = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__magic_name__ ) , __magic_name__ ) snake_case_ : Optional[Any] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) snake_case_ , snake_case_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Optional[Any] = True check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ : List[str] = True check_hidden_states_output(__magic_name__ , __magic_name__ , __magic_name__ ) def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" snake_case_ : List[Any] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' ) snake_case_ : Dict = np.load(_UpperCamelCase ) return list(_UpperCamelCase ) @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Any = TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __magic_name__ ) snake_case_ : List[str] = self.default_image_processor snake_case_ : List[str] = prepare_video() snake_case_ : int = image_processor(video[:8] , return_tensors='''pt''' ).to(__magic_name__ ) # forward pass with torch.no_grad(): snake_case_ : Union[str, Any] = model(**__magic_name__ ) # verify the logits snake_case_ : Any = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) snake_case_ : Any = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1e-4 ) )
60
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ = "▁" , __magic_name__ = True , __magic_name__ = "<unk>" , __magic_name__ = "</s>" , __magic_name__ = "<pad>" , ) -> Dict: '''simple docstring''' snake_case_ : List[Any] = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } snake_case_ : List[str] = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): snake_case_ : int = token_dict['''token'''] snake_case_ : Optional[int] = Tokenizer(Unigram() ) snake_case_ : int = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) snake_case_ : Optional[int] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ), pre_tokenizers.Digits(individual_digits=__magic_name__ ), pre_tokenizers.Punctuation(), ] ) snake_case_ : Tuple = decoders.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ) snake_case_ : Optional[Any] = TemplateProcessing( single=F'''$A {self.special_tokens["eos"]["token"]}''' , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) snake_case_ : Optional[Any] = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) if isinstance(__magic_name__ , __magic_name__ ): snake_case_ : Dict = [files] self._tokenizer.train(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> int: '''simple docstring''' snake_case_ : Any = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) self._tokenizer.train_from_iterator(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = json.loads(self._tokenizer.to_str() ) snake_case_ : Union[str, Any] = self.special_tokens['''unk''']['''id'''] snake_case_ : Tuple = Tokenizer.from_str(json.dumps(__magic_name__ ) )
60
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json''', '''tiiuae/falcon-7b''': '''https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = '''falcon''' lowerCamelCase_ : Any = ['''past_key_values'''] def __init__(self , __magic_name__=6_5024 , __magic_name__=4544 , __magic_name__=32 , __magic_name__=71 , __magic_name__=1e-5 , __magic_name__=0.02 , __magic_name__=True , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=None , __magic_name__=False , __magic_name__=False , __magic_name__=True , __magic_name__=True , __magic_name__=False , __magic_name__=11 , __magic_name__=11 , **__magic_name__ , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[Any] = vocab_size # Backward compatibility with n_embed kwarg snake_case_ : Dict = kwargs.pop('''n_embed''' , __magic_name__ ) snake_case_ : Optional[int] = hidden_size if n_embed is None else n_embed snake_case_ : List[str] = num_hidden_layers snake_case_ : List[str] = num_attention_heads snake_case_ : Optional[Any] = layer_norm_epsilon snake_case_ : List[str] = initializer_range snake_case_ : List[str] = use_cache snake_case_ : Optional[int] = hidden_dropout snake_case_ : List[Any] = attention_dropout snake_case_ : Any = bos_token_id snake_case_ : Dict = eos_token_id snake_case_ : Optional[Any] = num_attention_heads if num_kv_heads is None else num_kv_heads snake_case_ : Optional[Any] = alibi snake_case_ : Optional[int] = new_decoder_architecture snake_case_ : str = multi_query # Ignored when new_decoder_architecture is True snake_case_ : List[str] = parallel_attn snake_case_ : List[str] = bias super().__init__(bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) @property def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' return self.hidden_size // self.num_attention_heads @property def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' return not self.alibi
60
# 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 lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : List[Any] = [False] * len(_UpperCamelCase ) snake_case_ : int = [-1] * len(_UpperCamelCase ) def dfs(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Dict = True snake_case_ : Dict = 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 lowerCAmelCase_ = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
60
1
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def lowerCamelCase_ ( _UpperCamelCase ) -> List[str]: """simple docstring""" if not is_accelerate_available(): return method snake_case_ : Any = version.parse(accelerate.__version__ ).base_version if version.parse(_UpperCamelCase ) < version.parse('''0.17.0''' ): return method def wrapper(self , *_UpperCamelCase , **_UpperCamelCase ): if hasattr(self , '''_hf_hook''' ) and hasattr(self._hf_hook , '''pre_forward''' ): self._hf_hook.pre_forward(self ) return method(self , *_UpperCamelCase , **_UpperCamelCase ) return wrapper
60
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=False , ) -> int: '''simple docstring''' snake_case_ : int = size if size is not None else {'''height''': 20, '''width''': 20} snake_case_ : int = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} snake_case_ : str = parent snake_case_ : Optional[int] = batch_size snake_case_ : Dict = num_channels snake_case_ : List[Any] = image_size snake_case_ : Union[str, Any] = min_resolution snake_case_ : Tuple = max_resolution snake_case_ : str = do_resize snake_case_ : Tuple = size snake_case_ : int = do_center_crop snake_case_ : Tuple = crop_size snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean snake_case_ : List[str] = image_std snake_case_ : str = do_reduce_labels def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : Any = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Union[str, Any] = Image.open(dataset[0]['''file'''] ) snake_case_ : str = Image.open(dataset[1]['''file'''] ) return image, map def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : str = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Optional[Any] = Image.open(ds[0]['''file'''] ) snake_case_ : Optional[Any] = Image.open(ds[1]['''file'''] ) snake_case_ : List[str] = Image.open(ds[2]['''file'''] ) snake_case_ : str = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = BeitImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : int = BeitImageProcessingTester(self ) @property def lowerCamelCase (self ) -> str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_normalize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_mean''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_std''' ) ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) snake_case_ : Union[str, Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__magic_name__ ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' pass def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Optional[int] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : List[str] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) snake_case_ : Union[str, Any] = [] for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input snake_case_ : List[str] = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test not batched input (PIL images) snake_case_ , snake_case_ : Optional[int] = prepare_semantic_single_inputs() snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched input (PIL images) snake_case_ , snake_case_ : Dict = prepare_semantic_batch_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 snake_case_ , snake_case_ : Tuple = prepare_semantic_single_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 150 ) snake_case_ : List[Any] = True snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 )
60
1
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" if "model" in orig_key: snake_case_ : Optional[Any] = orig_key.replace('''model.''' , '''''' ) if "norm1" in orig_key: snake_case_ : Optional[int] = orig_key.replace('''norm1''' , '''attention.output.LayerNorm''' ) if "norm2" in orig_key: snake_case_ : Optional[int] = orig_key.replace('''norm2''' , '''output.LayerNorm''' ) if "norm" in orig_key: snake_case_ : List[str] = orig_key.replace('''norm''' , '''LayerNorm''' ) if "transformer" in orig_key: snake_case_ : List[str] = orig_key.split('''.''' )[0].split('''_''' )[-1] snake_case_ : Optional[Any] = orig_key.replace(f'''transformer_{layer_num}''' , f'''encoder.layer.{layer_num}''' ) if "mha.attn" in orig_key: snake_case_ : Dict = orig_key.replace('''mha.attn''' , '''attention.self''' ) if "mha" in orig_key: snake_case_ : Any = orig_key.replace('''mha''' , '''attention''' ) if "W_q" in orig_key: snake_case_ : Tuple = orig_key.replace('''W_q''' , '''self.query''' ) if "W_k" in orig_key: snake_case_ : List[str] = orig_key.replace('''W_k''' , '''self.key''' ) if "W_v" in orig_key: snake_case_ : Optional[int] = orig_key.replace('''W_v''' , '''self.value''' ) if "ff1" in orig_key: snake_case_ : Any = orig_key.replace('''ff1''' , '''intermediate.dense''' ) if "ff2" in orig_key: snake_case_ : Dict = orig_key.replace('''ff2''' , '''output.dense''' ) if "ff" in orig_key: snake_case_ : Union[str, Any] = orig_key.replace('''ff''' , '''output.dense''' ) if "mlm_class" in orig_key: snake_case_ : Optional[Any] = orig_key.replace('''mlm.mlm_class''' , '''cls.predictions.decoder''' ) if "mlm" in orig_key: snake_case_ : Dict = orig_key.replace('''mlm''' , '''cls.predictions.transform''' ) if "cls" not in orig_key: snake_case_ : Optional[int] = '''yoso.''' + orig_key return orig_key def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case_ : Union[str, Any] = orig_state_dict.pop(_UpperCamelCase ) if ("pooler" in key) or ("sen_class" in key): continue else: snake_case_ : Dict = val snake_case_ : int = orig_state_dict['''cls.predictions.decoder.bias'''] snake_case_ : Optional[int] = torch.arange(_UpperCamelCase ).expand((1, -1) ) + 2 return orig_state_dict def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : Tuple = torch.load(_UpperCamelCase , map_location='''cpu''' )['''model_state_dict'''] snake_case_ : Union[str, Any] = YosoConfig.from_json_file(_UpperCamelCase ) snake_case_ : Tuple = YosoForMaskedLM(_UpperCamelCase ) snake_case_ : Any = convert_checkpoint_helper(config.max_position_embeddings , _UpperCamelCase ) print(model.load_state_dict(_UpperCamelCase ) ) model.eval() model.save_pretrained(_UpperCamelCase ) print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--pytorch_model_path''', default=None, type=str, required=True, help='''Path to YOSO pytorch checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The json file for YOSO model config.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase_ = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
60
from sklearn.metrics import mean_squared_error import datasets lowerCAmelCase_ = '''\ @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} } ''' lowerCAmelCase_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' lowerCAmelCase_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__="uniform_average" , __magic_name__=True ) -> Any: '''simple docstring''' snake_case_ : List[Any] = mean_squared_error( __magic_name__ , __magic_name__ , sample_weight=__magic_name__ , multioutput=__magic_name__ , squared=__magic_name__ ) return {"mse": mse}
60
1
from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCAmelCase_ = TypeVar('''KT''') lowerCAmelCase_ = TypeVar('''VT''') class __lowerCAmelCase ( Generic[KT, VT] ): def __init__(self , __magic_name__ = "root" , __magic_name__ = None ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = key snake_case_ : Dict = value snake_case_ : list[Node[KT, VT]] = [] def __repr__(self ) -> str: '''simple docstring''' return F'''Node({self.key}: {self.value})''' @property def lowerCamelCase (self ) -> int: '''simple docstring''' return len(self.forward ) class __lowerCAmelCase ( Generic[KT, VT] ): def __init__(self , __magic_name__ = 0.5 , __magic_name__ = 16 ) -> Optional[Any]: '''simple docstring''' snake_case_ : Node[KT, VT] = Node[KT, VT]() snake_case_ : Dict = 0 snake_case_ : Any = p snake_case_ : Optional[Any] = max_level def __str__(self ) -> str: '''simple docstring''' snake_case_ : Dict = list(self ) if len(__magic_name__ ) == 0: return F'''SkipList(level={self.level})''' snake_case_ : int = max((len(str(__magic_name__ ) ) for item in items) , default=4 ) snake_case_ : Optional[Any] = max(__magic_name__ , 4 ) + 4 snake_case_ : Union[str, Any] = self.head snake_case_ : Any = [] snake_case_ : int = node.forward.copy() lines.append(F'''[{node.key}]'''.ljust(__magic_name__ , '''-''' ) + '''* ''' * len(__magic_name__ ) ) lines.append(''' ''' * label_size + '''| ''' * len(__magic_name__ ) ) while len(node.forward ) != 0: snake_case_ : List[str] = node.forward[0] lines.append( F'''[{node.key}]'''.ljust(__magic_name__ , '''-''' ) + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) ) lines.append(''' ''' * label_size + '''| ''' * len(__magic_name__ ) ) snake_case_ : List[Any] = node.forward lines.append('''None'''.ljust(__magic_name__ ) + '''* ''' * len(__magic_name__ ) ) return F'''SkipList(level={self.level})\n''' + "\n".join(__magic_name__ ) def __iter__(self ) -> str: '''simple docstring''' snake_case_ : int = self.head while len(node.forward ) != 0: yield node.forward[0].key snake_case_ : List[str] = node.forward[0] def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[int] = 1 while random() < self.p and level < self.max_level: level += 1 return level def lowerCamelCase (self , __magic_name__ ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: '''simple docstring''' snake_case_ : List[Any] = [] snake_case_ : Union[str, Any] = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: snake_case_ : List[str] = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(__magic_name__ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ : Union[str, Any] = self._locate_node(__magic_name__ ) if node is not None: for i, update_node in enumerate(__magic_name__ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: snake_case_ : List[Any] = node.forward[i] else: snake_case_ : Any = update_node.forward[:i] def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ : int = self._locate_node(__magic_name__ ) if node is not None: snake_case_ : Optional[int] = value else: snake_case_ : List[str] = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , __magic_name__ ): update_vector.append(self.head ) snake_case_ : List[str] = level snake_case_ : Any = Node(__magic_name__ , __magic_name__ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(__magic_name__ ) else: snake_case_ : Tuple = new_node def lowerCamelCase (self , __magic_name__ ) -> VT | None: '''simple docstring''' snake_case_ , snake_case_ : int = self._locate_node(__magic_name__ ) if node is not None: return node.value return None def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : int = SkipList() skip_list.insert('''Key1''' , 3 ) skip_list.insert('''Key2''' , 12 ) skip_list.insert('''Key3''' , 41 ) skip_list.insert('''Key4''' , -19 ) snake_case_ : Optional[Any] = skip_list.head snake_case_ : Optional[int] = {} while node.level != 0: snake_case_ : Optional[Any] = node.forward[0] snake_case_ : Union[str, Any] = node.value assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[Any] = SkipList() skip_list.insert('''Key1''' , 10 ) skip_list.insert('''Key1''' , 12 ) skip_list.insert('''Key5''' , 7 ) skip_list.insert('''Key7''' , 10 ) skip_list.insert('''Key10''' , 5 ) skip_list.insert('''Key7''' , 7 ) skip_list.insert('''Key5''' , 5 ) skip_list.insert('''Key10''' , 10 ) snake_case_ : str = skip_list.head snake_case_ : Tuple = {} while node.level != 0: snake_case_ : List[str] = node.forward[0] snake_case_ : Union[str, Any] = node.value if len(_UpperCamelCase ) != 4: print() assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def lowerCamelCase_ ( ) -> int: """simple docstring""" snake_case_ : Optional[Any] = SkipList() assert skip_list.find('''Some key''' ) is None def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = SkipList() skip_list.insert('''Key2''' , 20 ) assert skip_list.find('''Key2''' ) == 20 skip_list.insert('''Some Key''' , 10 ) skip_list.insert('''Key2''' , 8 ) skip_list.insert('''V''' , 13 ) assert skip_list.find('''Y''' ) is None assert skip_list.find('''Key2''' ) == 8 assert skip_list.find('''Some Key''' ) == 10 assert skip_list.find('''V''' ) == 13 def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[Any] = SkipList() skip_list.delete('''Some key''' ) assert len(skip_list.head.forward ) == 0 def lowerCamelCase_ ( ) -> int: """simple docstring""" snake_case_ : Union[str, Any] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" snake_case_ : Optional[int] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) == 14 assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''X''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key1''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : int = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 142 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''X''' ) def traverse_keys(_UpperCamelCase ): yield node.key for forward_node in node.forward: yield from traverse_keys(_UpperCamelCase ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" def is_sorted(_UpperCamelCase ): return all(next_item >= item for item, next_item in zip(_UpperCamelCase , lst[1:] ) ) snake_case_ : str = SkipList() for i in range(10 ): skip_list.insert(_UpperCamelCase , _UpperCamelCase ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(_UpperCamelCase ) ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : Optional[Any] = SkipList() skip_list.insert(2 , '''2''' ) skip_list.insert(4 , '''4''' ) skip_list.insert(6 , '''4''' ) skip_list.insert(4 , '''5''' ) skip_list.insert(8 , '''4''' ) skip_list.insert(9 , '''4''' ) skip_list.delete(4 ) print(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class __lowerCAmelCase : lowerCamelCase_ : Any = None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) snake_case_ : List[Any] = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Optional[int] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : str = self.feature_extraction_class.from_json_file(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : str = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : Dict = self.feature_extraction_class.from_pretrained(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class() self.assertIsNotNone(__magic_name__ )
60
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : str = None @staticmethod def lowerCamelCase () -> Any: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def lowerCamelCase (cls ) -> List[Any]: '''simple docstring''' return F'''`pip install {cls.pip_package or cls.name}`''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[int] = '''optuna''' @staticmethod def lowerCamelCase () -> Union[str, Any]: '''simple docstring''' return is_optuna_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Union[str, Any]: '''simple docstring''' return run_hp_search_optuna(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_optuna(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''ray''' lowerCamelCase_ : List[str] = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase () -> List[Any]: '''simple docstring''' return is_ray_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_ray(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_ray(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''sigopt''' @staticmethod def lowerCamelCase () -> Optional[int]: '''simple docstring''' return is_sigopt_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> List[str]: '''simple docstring''' return run_hp_search_sigopt(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' return default_hp_space_sigopt(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''wandb''' @staticmethod def lowerCamelCase () -> Dict: '''simple docstring''' return is_wandb_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_wandb(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return default_hp_space_wandb(__magic_name__ ) lowerCAmelCase_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_UpperCamelCase ) > 0: snake_case_ : Dict = available_backends[0].name if len(_UpperCamelCase ) > 1: logger.info( f'''{len(_UpperCamelCase )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( f''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
60
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase_ = 1_6 lowerCAmelCase_ = 3_2 def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase = 16 ) -> List[str]: """simple docstring""" snake_case_ : List[Any] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) snake_case_ : List[str] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(_UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) snake_case_ : Optional[Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=_UpperCamelCase , max_length=_UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): snake_case_ : List[Any] = datasets.map( _UpperCamelCase , batched=_UpperCamelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library snake_case_ : Any = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(_UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case_ : Dict = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case_ : Union[str, Any] = 16 elif accelerator.mixed_precision != "no": snake_case_ : Union[str, Any] = 8 else: snake_case_ : Optional[int] = None return tokenizer.pad( _UpperCamelCase , padding='''longest''' , max_length=_UpperCamelCase , pad_to_multiple_of=_UpperCamelCase , return_tensors='''pt''' , ) # Instantiate dataloaders. snake_case_ : List[Any] = DataLoader( tokenized_datasets['''train'''] , shuffle=_UpperCamelCase , collate_fn=_UpperCamelCase , batch_size=_UpperCamelCase ) snake_case_ : List[Any] = DataLoader( tokenized_datasets['''validation'''] , shuffle=_UpperCamelCase , collate_fn=_UpperCamelCase , batch_size=_UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase_ = mocked_dataloaders # noqa: F811 def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , _UpperCamelCase ) == "1": snake_case_ : Tuple = 2 # New Code # snake_case_ : Optional[Any] = int(args.gradient_accumulation_steps ) snake_case_ : List[Any] = int(args.local_sgd_steps ) # Initialize accelerator snake_case_ : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=_UpperCamelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError('''LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)''' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs snake_case_ : Union[str, Any] = config['''lr'''] snake_case_ : Any = int(config['''num_epochs'''] ) snake_case_ : Dict = int(config['''seed'''] ) snake_case_ : int = int(config['''batch_size'''] ) snake_case_ : Tuple = evaluate.load('''glue''' , '''mrpc''' ) set_seed(_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = get_dataloaders(_UpperCamelCase , _UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case_ : Any = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=_UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). snake_case_ : Any = model.to(accelerator.device ) # Instantiate optimizer snake_case_ : Tuple = AdamW(params=model.parameters() , lr=_UpperCamelCase ) # Instantiate scheduler snake_case_ : Any = get_linear_schedule_with_warmup( optimizer=_UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCamelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ : Union[str, Any] = accelerator.prepare( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Now we train the model for epoch in range(_UpperCamelCase ): model.train() with LocalSGD( accelerator=_UpperCamelCase , model=_UpperCamelCase , local_sgd_steps=_UpperCamelCase , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(_UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(_UpperCamelCase ): snake_case_ : Union[str, Any] = model(**_UpperCamelCase ) snake_case_ : int = output.loss accelerator.backward(_UpperCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(_UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case_ : Dict = model(**_UpperCamelCase ) snake_case_ : Any = outputs.logits.argmax(dim=-1 ) snake_case_ , snake_case_ : int = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=_UpperCamelCase , references=_UpperCamelCase , ) snake_case_ : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , _UpperCamelCase ) def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" snake_case_ : List[Any] = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=_UpperCamelCase , default=_UpperCamelCase , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) # New Code # parser.add_argument( '''--gradient_accumulation_steps''' , type=_UpperCamelCase , default=1 , help='''The number of minibatches to be ran before gradients are accumulated.''' , ) parser.add_argument( '''--local_sgd_steps''' , type=_UpperCamelCase , default=8 , help='''Number of local SGD steps or None to disable local SGD''' ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) snake_case_ : str = parser.parse_args() snake_case_ : str = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(_UpperCamelCase , _UpperCamelCase ) if __name__ == "__main__": main()
60
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> list: """simple docstring""" snake_case_ : Tuple = len(_UpperCamelCase ) snake_case_ : Union[str, Any] = [[0] * n for i in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): snake_case_ : Any = y_points[i] for i in range(2 , _UpperCamelCase ): for j in range(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[int] = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
60
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_mobilebert''': [ '''MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileBertConfig''', '''MobileBertOnnxConfig''', ], '''tokenization_mobilebert''': ['''MobileBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''MobileBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileBertForMaskedLM''', '''MobileBertForMultipleChoice''', '''MobileBertForNextSentencePrediction''', '''MobileBertForPreTraining''', '''MobileBertForQuestionAnswering''', '''MobileBertForSequenceClassification''', '''MobileBertForTokenClassification''', '''MobileBertLayer''', '''MobileBertModel''', '''MobileBertPreTrainedModel''', '''load_tf_weights_in_mobilebert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileBertForMaskedLM''', '''TFMobileBertForMultipleChoice''', '''TFMobileBertForNextSentencePrediction''', '''TFMobileBertForPreTraining''', '''TFMobileBertForQuestionAnswering''', '''TFMobileBertForSequenceClassification''', '''TFMobileBertForTokenClassification''', '''TFMobileBertMainLayer''', '''TFMobileBertModel''', '''TFMobileBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
1
def __lowercase ( snake_case ): """simple docstring""" if not isinstance(snake_case, snake_case ): raise ValueError('''Input must be an integer''' ) if input_num <= 0: raise ValueError('''Input must be positive''' ) return sum( divisor for divisor in range(1, input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
0
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" return getitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" return setitem, k, v def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" return delitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) -> str: """simple docstring""" try: return fun(_UpperCamelCase , *_UpperCamelCase ), None except Exception as e: return None, e lowerCAmelCase_ = ( _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), ) lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_a''', '''val_b'''), ] lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), _del('''key_a'''), _del('''key_b'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), ] lowerCAmelCase_ = [ _get('''key_a'''), _del('''key_a'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), _del('''key_a'''), _get('''key_a'''), ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('''key_a''', '''val_b'''), ] @pytest.mark.parametrize( '''operations''' , ( pytest.param(_add_items , id='''add items''' ), pytest.param(_overwrite_items , id='''overwrite items''' ), pytest.param(_delete_items , id='''delete items''' ), pytest.param(_access_absent_items , id='''access absent items''' ), pytest.param(_add_with_resize_up , id='''add with resize up''' ), pytest.param(_add_with_resize_down , id='''add with resize down''' ), ) , ) def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Any = HashMap(initial_block_size=4 ) snake_case_ : Union[str, Any] = {} for _, (fun, *args) in enumerate(_UpperCamelCase ): snake_case_ , snake_case_ : str = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) assert my_res == py_res assert str(_UpperCamelCase ) == str(_UpperCamelCase ) assert set(_UpperCamelCase ) == set(_UpperCamelCase ) assert len(_UpperCamelCase ) == len(_UpperCamelCase ) assert set(my.items() ) == set(py.items() ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" def is_public(_UpperCamelCase ) -> bool: return not name.startswith('''_''' ) snake_case_ : str = {name for name in dir({} ) if is_public(_UpperCamelCase )} snake_case_ : str = {name for name in dir(HashMap() ) if is_public(_UpperCamelCase )} assert dict_public_names > hash_public_names
60
0
import re from filelock import FileLock try: import nltk __snake_case = True except (ImportError, ModuleNotFoundError): __snake_case = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def _A ( _lowercase ) -> str: """simple docstring""" re.sub('<n>' , '' , _lowercase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_lowercase ) )
1
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase ) -> list: """simple docstring""" if len(_UpperCamelCase ) == 0: return [] snake_case_ , snake_case_ : Dict = min(_UpperCamelCase ), max(_UpperCamelCase ) snake_case_ : List[str] = int(max_value - min_value ) + 1 snake_case_ : list[list] = [[] for _ in range(_UpperCamelCase )] for i in my_list: buckets[int(i - min_value )].append(_UpperCamelCase ) return [v for bucket in buckets for v in sorted(_UpperCamelCase )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -1_0, 1_5, 2, -2]) == [-1_0, -2, 0, 1, 2, 1_5]
60
0
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCamelCase__ : """simple docstring""" @staticmethod def snake_case_ ( *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Tuple ) -> List[Any]: pass @is_pipeline_test @require_torch @require_vision class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" a__ : Tuple = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def snake_case_ ( self : Tuple , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] ) -> int: _A = pipeline('''visual-question-answering''' , model='''hf-internal-testing/tiny-vilt-random-vqa''' ) _A = [ { '''image''': Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''question''': '''How many cats are there?''', }, { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''question''': '''How many cats are there?''', }, ] return vqa_pipeline, examples def snake_case_ ( self : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Tuple ) -> Tuple: _A = vqa_pipeline(__lowerCAmelCase , top_k=1 ) self.assertEqual( __lowerCAmelCase , [ [{'''score''': ANY(__lowerCAmelCase ), '''answer''': ANY(__lowerCAmelCase )}], [{'''score''': ANY(__lowerCAmelCase ), '''answer''': ANY(__lowerCAmelCase )}], ] , ) @require_torch def snake_case_ ( self : Dict ) -> Any: _A = pipeline('''visual-question-answering''' , model='''hf-internal-testing/tiny-vilt-random-vqa''' ) _A = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' _A = '''How many cats are there?''' _A = vqa_pipeline(image=__lowerCAmelCase , question='''How many cats are there?''' , top_k=2 ) self.assertEqual( __lowerCAmelCase , [{'''score''': ANY(__lowerCAmelCase ), '''answer''': ANY(__lowerCAmelCase )}, {'''score''': ANY(__lowerCAmelCase ), '''answer''': ANY(__lowerCAmelCase )}] ) _A = vqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( __lowerCAmelCase , [{'''score''': ANY(__lowerCAmelCase ), '''answer''': ANY(__lowerCAmelCase )}, {'''score''': ANY(__lowerCAmelCase ), '''answer''': ANY(__lowerCAmelCase )}] ) @slow @require_torch def snake_case_ ( self : Dict ) -> List[str]: _A = pipeline('''visual-question-answering''' , model='''dandelin/vilt-b32-finetuned-vqa''' ) _A = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' _A = '''How many cats are there?''' _A = vqa_pipeline(image=__lowerCAmelCase , question=__lowerCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [{'''score''': 0.8799, '''answer''': '''2'''}, {'''score''': 0.296, '''answer''': '''1'''}] ) _A = vqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [{'''score''': 0.8799, '''answer''': '''2'''}, {'''score''': 0.296, '''answer''': '''1'''}] ) _A = vqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [[{'''score''': 0.8799, '''answer''': '''2'''}, {'''score''': 0.296, '''answer''': '''1'''}]] * 2 , ) @require_tf @unittest.skip('''Visual question answering not implemented in TF''' ) def snake_case_ ( self : Union[str, Any] ) -> List[Any]: pass
2
import tensorflow as tf from ...tf_utils import shape_list class __lowerCAmelCase ( tf.keras.layers.Layer ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=1 , __magic_name__=False , **__magic_name__ ) -> Dict: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[Any] = vocab_size snake_case_ : Dict = d_embed snake_case_ : Union[str, Any] = d_proj snake_case_ : str = cutoffs + [vocab_size] snake_case_ : int = [0] + self.cutoffs snake_case_ : Optional[int] = div_val snake_case_ : int = self.cutoffs[0] snake_case_ : Any = len(self.cutoffs ) - 1 snake_case_ : Union[str, Any] = self.shortlist_size + self.n_clusters snake_case_ : str = keep_order snake_case_ : int = [] snake_case_ : Union[str, Any] = [] def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' if self.n_clusters > 0: snake_case_ : Tuple = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_weight''' ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_bias''' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: snake_case_ : List[str] = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' , ) self.out_projs.append(__magic_name__ ) else: self.out_projs.append(__magic_name__ ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : List[str] = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] snake_case_ : Optional[Any] = self.d_embed // (self.div_val**i) snake_case_ : int = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' ) self.out_projs.append(__magic_name__ ) snake_case_ : int = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : Any = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) super().build(__magic_name__ ) @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = x if proj is not None: snake_case_ : List[str] = tf.einsum('''ibd,ed->ibe''' , __magic_name__ , __magic_name__ ) return tf.einsum('''ibd,nd->ibn''' , __magic_name__ , __magic_name__ ) + b @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = shape_list(__magic_name__ ) snake_case_ : Tuple = tf.range(lp_size[0] , dtype=target.dtype ) snake_case_ : Dict = tf.stack([r, target] , 1 ) return tf.gather_nd(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=True , __magic_name__=False ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = 0 if self.n_clusters == 0: snake_case_ : Any = self._logit(__magic_name__ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: snake_case_ : Union[str, Any] = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__magic_name__ , logits=__magic_name__ ) snake_case_ : Optional[Any] = tf.nn.log_softmax(__magic_name__ , axis=-1 ) else: snake_case_ : Optional[int] = shape_list(__magic_name__ ) snake_case_ : int = [] snake_case_ : List[Any] = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: snake_case_ : str = (target >= l_idx) & (target < r_idx) snake_case_ : Dict = tf.where(__magic_name__ ) snake_case_ : List[str] = tf.boolean_mask(__magic_name__ , __magic_name__ ) - l_idx if self.div_val == 1: snake_case_ : Any = self.out_layers[0][0][l_idx:r_idx] snake_case_ : Dict = self.out_layers[0][1][l_idx:r_idx] else: snake_case_ : Union[str, Any] = self.out_layers[i][0] snake_case_ : int = self.out_layers[i][1] if i == 0: snake_case_ : List[Any] = tf.concat([cur_W, self.cluster_weight] , 0 ) snake_case_ : Tuple = tf.concat([cur_b, self.cluster_bias] , 0 ) snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[0] ) snake_case_ : Any = tf.nn.log_softmax(__magic_name__ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = self._gather_logprob(__magic_name__ , __magic_name__ ) else: snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[i] ) snake_case_ : Union[str, Any] = tf.nn.log_softmax(__magic_name__ ) snake_case_ : Optional[Any] = self.cutoffs[0] + i - 1 # No probability for the head cluster snake_case_ : Optional[int] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(__magic_name__ ) if target is not None: snake_case_ : Any = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : str = self._gather_logprob(__magic_name__ , __magic_name__ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(__magic_name__ , -cur_logprob , shape_list(__magic_name__ ) ) snake_case_ : str = tf.concat(__magic_name__ , axis=-1 ) if target is not None: if return_mean: snake_case_ : int = tf.reduce_mean(__magic_name__ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(__magic_name__ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(__magic_name__ , name=self.name , aggregation='''mean''' if return_mean else '''''' ) return out
60
0
'''simple docstring''' import os from datetime import datetime as dt from github import Github lowerCAmelCase : List[str] = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def A_( ): UpperCamelCase = Github(os.environ['GITHUB_TOKEN']) UpperCamelCase = g.get_repo('huggingface/diffusers') UpperCamelCase = repo.get_issues(state='open') for issue in open_issues: UpperCamelCase = sorted(issue.get_comments() , key=lambda A: i.created_at , reverse=A) UpperCamelCase = comments[0] if len(A) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state='closed') elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state='open') issue.remove_from_labels('stale') elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.') issue.add_to_labels('stale') if __name__ == "__main__": main()
3
import requests def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" snake_case_ : Tuple = {'''Content-Type''': '''application/json'''} snake_case_ : Any = requests.post(_UpperCamelCase , json={'''text''': message_body} , headers=_UpperCamelCase ) if response.status_code != 200: snake_case_ : List[Any] = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_UpperCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('''<YOUR MESSAGE BODY>''', '''<SLACK CHANNEL URL>''')
60
0
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int ): 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(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _SCREAMING_SNAKE_CASE (): lowerCAmelCase = 2 while True: if is_prime(_UpperCAmelCase ): yield num num += 1 def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int = 200_0000 ): return sum(takewhile(lambda _UpperCAmelCase : x < n , prime_generator() ) ) if __name__ == "__main__": print(f'''{solution() = }''')
4
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
'''simple docstring''' import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging _lowercase = logging.get_logger(__name__) def A (__lowerCamelCase :List[str] ): _lowerCAmelCase = r"""\w+[.]\d+""" _lowerCAmelCase = re.findall(__lowerCamelCase , __lowerCamelCase ) for pat in pats: _lowerCAmelCase = key.replace(__lowerCamelCase , """_""".join(pat.split(""".""" ) ) ) return key def A (__lowerCamelCase :Union[str, Any] , __lowerCamelCase :Any , __lowerCamelCase :int ): _lowerCAmelCase = pt_tuple_key[:-1] + ("""scale""",) if ( any("""norm""" in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): _lowerCAmelCase = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: _lowerCAmelCase = pt_tuple_key[:-1] + ("""scale""",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: _lowerCAmelCase = pt_tuple_key[:-1] + ("""embedding""",) return renamed_pt_tuple_key, pt_tensor # conv layer _lowerCAmelCase = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: _lowerCAmelCase = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer _lowerCAmelCase = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight": _lowerCAmelCase = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight _lowerCAmelCase = pt_tuple_key[:-1] + ("""weight""",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias _lowerCAmelCase = pt_tuple_key[:-1] + ("""bias""",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def A (__lowerCamelCase :Any , __lowerCamelCase :int , __lowerCamelCase :Dict=42 ): # Step 1: Convert pytorch tensor to numpy _lowerCAmelCase = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params _lowerCAmelCase = flax_model.init_weights(PRNGKey(__lowerCamelCase ) ) _lowerCAmelCase = flatten_dict(__lowerCamelCase ) _lowerCAmelCase = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _lowerCAmelCase = rename_key(__lowerCamelCase ) _lowerCAmelCase = tuple(renamed_pt_key.split(""".""" ) ) # Correctly rename weight parameters _lowerCAmelCase , _lowerCAmelCase = rename_key_and_reshape_tensor(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ' f'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) # also add unexpected weight so that warning is thrown _lowerCAmelCase = jnp.asarray(__lowerCamelCase ) return unflatten_dict(__lowerCamelCase )
5
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''', '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''', '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''owlvit_text_model''' def __init__(self , __magic_name__=4_9408 , __magic_name__=512 , __magic_name__=2048 , __magic_name__=12 , __magic_name__=8 , __magic_name__=16 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , __magic_name__=0 , __magic_name__=4_9406 , __magic_name__=4_9407 , **__magic_name__ , ) -> str: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : int = vocab_size snake_case_ : str = hidden_size snake_case_ : List[Any] = intermediate_size snake_case_ : str = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : str = hidden_act snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : Union[str, Any] = initializer_range snake_case_ : int = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : str = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit_vision_model''' def __init__(self , __magic_name__=768 , __magic_name__=3072 , __magic_name__=12 , __magic_name__=12 , __magic_name__=3 , __magic_name__=768 , __magic_name__=32 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : Union[str, Any] = intermediate_size snake_case_ : Union[str, Any] = num_hidden_layers snake_case_ : Tuple = num_attention_heads snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = image_size snake_case_ : Dict = patch_size snake_case_ : List[Any] = hidden_act snake_case_ : Tuple = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : List[str] = initializer_range snake_case_ : List[Any] = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : int = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit''' lowerCamelCase_ : Optional[int] = True def __init__(self , __magic_name__=None , __magic_name__=None , __magic_name__=512 , __magic_name__=2.6_592 , __magic_name__=True , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) if text_config is None: snake_case_ : Tuple = {} logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''' ) if vision_config is None: snake_case_ : str = {} logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''' ) snake_case_ : str = OwlViTTextConfig(**__magic_name__ ) snake_case_ : Union[str, Any] = OwlViTVisionConfig(**__magic_name__ ) snake_case_ : Any = projection_dim snake_case_ : Union[str, Any] = logit_scale_init_value snake_case_ : str = return_dict snake_case_ : Any = 1.0 @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = cls.get_config_dict(__magic_name__ , **__magic_name__ ) 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(__magic_name__ , **__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> str: '''simple docstring''' snake_case_ : Optional[int] = {} snake_case_ : Union[str, Any] = text_config snake_case_ : Optional[Any] = vision_config return cls.from_dict(__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = copy.deepcopy(self.__dict__ ) snake_case_ : List[Any] = self.text_config.to_dict() snake_case_ : List[Any] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ] ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''logits_per_image''', {0: '''batch'''}), ('''logits_per_text''', {0: '''batch'''}), ('''text_embeds''', {0: '''batch'''}), ('''image_embeds''', {0: '''batch'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-4 def lowerCamelCase (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Dict = super().generate_dummy_inputs( processor.tokenizer , batch_size=__magic_name__ , seq_length=__magic_name__ , framework=__magic_name__ ) snake_case_ : List[str] = super().generate_dummy_inputs( processor.image_processor , batch_size=__magic_name__ , framework=__magic_name__ ) return {**text_input_dict, **image_input_dict} @property def lowerCamelCase (self ) -> int: '''simple docstring''' return 14
60
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Union[str, Any]=4 , __A :Dict=3 , __A :str=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Tuple=[2, 4, 8, 16] , __A :List[str]=7 , __A :Optional[Any]=3.0 , __A :Tuple=True , __A :Tuple=0.0 , __A :Dict=0.0 , __A :Tuple=0.1 , __A :str="gelu" , __A :Tuple=0.0_2 , __A :str=1E-5 , __A :Tuple=0.0 , __A :List[str]=None , __A :Optional[Any]=None , **__A :Optional[Any] , ) -> List[str]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
6
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) lowerCamelCase_ : Union[str, Any] = ['''accelerate''', '''launch'''] lowerCamelCase_ : Tuple = Path.home() / '''.cache/huggingface/accelerate''' lowerCamelCase_ : Tuple = '''default_config.yaml''' lowerCamelCase_ : str = config_folder / config_file lowerCamelCase_ : List[Any] = config_folder / '''_default_config.yaml''' lowerCamelCase_ : Dict = Path('''tests/test_configs''' ) @classmethod def lowerCamelCase (cls ) -> Dict: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCamelCase (cls ) -> Any: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=__magic_name__ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(__magic_name__ ), self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''test-tpu''' lowerCamelCase_ : Dict = '''us-central1-a''' lowerCamelCase_ : Any = '''ls''' lowerCamelCase_ : Dict = ['''accelerate''', '''tpu-config'''] lowerCamelCase_ : Tuple = '''cd /usr/share''' lowerCamelCase_ : List[Any] = '''tests/test_samples/test_command_file.sh''' lowerCamelCase_ : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : int = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=__magic_name__ ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , )
60
0
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('foo.json',)] ) def lowerCAmelCase_ ( self : Union[str, Any] , _UpperCAmelCase : str ): _A = GenerationConfig( do_sample=_UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_UpperCAmelCase , config_name=_UpperCAmelCase ) _A = GenerationConfig.from_pretrained(_UpperCAmelCase , config_name=_UpperCAmelCase ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , _UpperCAmelCase ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , _UpperCAmelCase ) def lowerCAmelCase_ ( self : Union[str, Any] ): _A = AutoConfig.from_pretrained('gpt2' ) _A = GenerationConfig.from_model_config(_UpperCAmelCase ) _A = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def lowerCAmelCase_ ( self : Dict ): _A = GenerationConfig() _A = { 'max_new_tokens': 1_024, 'foo': 'bar', } _A = copy.deepcopy(_UpperCAmelCase ) _A = generation_config.update(**_UpperCAmelCase ) # update_kwargs was not modified (no side effects) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1_024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(_UpperCAmelCase , {'foo': 'bar'} ) def lowerCAmelCase_ ( self : str ): _A = GenerationConfig() _A = 'bar' with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir: generation_config.save_pretrained(_UpperCAmelCase ) _A = GenerationConfig.from_pretrained(_UpperCAmelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , 'bar' ) _A = GenerationConfig.from_model_config(_UpperCAmelCase ) assert not hasattr(_UpperCAmelCase , 'foo' ) # no new kwargs should be initialized if from config def lowerCAmelCase_ ( self : Any ): _A = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , _UpperCAmelCase ) self.assertEqual(default_config.num_beams , 1 ) _A = GenerationConfig( do_sample=_UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , _UpperCAmelCase ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_UpperCAmelCase ) _A = GenerationConfig.from_pretrained(_UpperCAmelCase , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , _UpperCAmelCase ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' @classmethod def lowerCAmelCase_ ( cls : Any ): _A = TOKEN HfFolder.save_token(_UpperCAmelCase ) @classmethod def lowerCAmelCase_ ( cls : str ): try: delete_repo(token=cls._token , repo_id='test-generation-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-generation-config-org' ) except HTTPError: pass def lowerCAmelCase_ ( self : List[Any] ): _A = GenerationConfig( do_sample=_UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('test-generation-config' , use_auth_token=self._token ) _A = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_UpperCAmelCase , getattr(_UpperCAmelCase , _UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='test-generation-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _UpperCAmelCase , repo_id='test-generation-config' , push_to_hub=_UpperCAmelCase , use_auth_token=self._token ) _A = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_UpperCAmelCase , getattr(_UpperCAmelCase , _UpperCAmelCase ) ) def lowerCAmelCase_ ( self : Any ): _A = GenerationConfig( do_sample=_UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('valid_org/test-generation-config-org' , use_auth_token=self._token ) _A = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_UpperCAmelCase , getattr(_UpperCAmelCase , _UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-generation-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _UpperCAmelCase , repo_id='valid_org/test-generation-config-org' , push_to_hub=_UpperCAmelCase , use_auth_token=self._token ) _A = GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_UpperCAmelCase , getattr(_UpperCAmelCase , _UpperCAmelCase ) )
7
import warnings from ..trainer import Trainer from ..utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__=None , **__magic_name__ ) -> Dict: '''simple docstring''' warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , __magic_name__ , ) super().__init__(args=__magic_name__ , **__magic_name__ )
60
0
'''simple docstring''' import inspect import unittest from transformers import YolosConfig 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE : def __init__( self , _UpperCAmelCase , _UpperCAmelCase=13 , _UpperCAmelCase=[30, 30] , _UpperCAmelCase=2 , _UpperCAmelCase=3 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=32 , _UpperCAmelCase=5 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=10 , _UpperCAmelCase=0.02 , _UpperCAmelCase=3 , _UpperCAmelCase=None , _UpperCAmelCase=8 , _UpperCAmelCase=10 , ): '''simple docstring''' __A : Union[str, Any] = parent __A : Tuple = batch_size __A : List[str] = image_size __A : Dict = patch_size __A : Optional[Any] = num_channels __A : Tuple = is_training __A : Dict = use_labels __A : List[Any] = hidden_size __A : Tuple = num_hidden_layers __A : int = num_attention_heads __A : Optional[int] = intermediate_size __A : Tuple = hidden_act __A : Any = hidden_dropout_prob __A : Optional[Any] = attention_probs_dropout_prob __A : List[Any] = type_sequence_label_size __A : List[Any] = initializer_range __A : Optional[int] = num_labels __A : List[Any] = scope __A : Any = n_targets __A : Union[str, Any] = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens __A : List[str] = (image_size[1] // patch_size) * (image_size[0] // patch_size) __A : int = num_patches + 1 + self.num_detection_tokens def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]) __A : Tuple = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) __A : List[Any] = [] for i in range(self.batch_size): __A : Optional[int] = {} __A : Union[str, Any] = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=_UpperCAmelCase) __A : str = torch.rand(self.n_targets , 4 , device=_UpperCAmelCase) labels.append(_UpperCAmelCase) __A : Any = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' return YolosConfig( 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 , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Any = YolosModel(config=_UpperCAmelCase) model.to(_UpperCAmelCase) model.eval() __A : Dict = model(_UpperCAmelCase) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size)) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : Any = YolosForObjectDetection(_UpperCAmelCase) model.to(_UpperCAmelCase) model.eval() __A : str = model(pixel_values=_UpperCAmelCase) __A : List[str] = model(_UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4)) __A : Union[str, Any] = model(pixel_values=_UpperCAmelCase , labels=_UpperCAmelCase) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4)) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = self.prepare_config_and_inputs() __A ,__A ,__A : Tuple = config_and_inputs __A : Tuple = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE (a__ , a__ , unittest.TestCase ): lowerCAmelCase = (YolosModel, YolosForObjectDetection) if is_torch_available() else () lowerCAmelCase = ( {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {} ) lowerCAmelCase = False lowerCAmelCase = False lowerCAmelCase = False lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False): '''simple docstring''' __A : Optional[Any] = super()._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase , return_labels=_UpperCAmelCase) if return_labels: if model_class.__name__ == "YolosForObjectDetection": __A : Any = [] for i in range(self.model_tester.batch_size): __A : Tuple = {} __A : Tuple = torch.ones( size=(self.model_tester.n_targets,) , device=_UpperCAmelCase , dtype=torch.long) __A : Optional[Any] = torch.ones( self.model_tester.n_targets , 4 , device=_UpperCAmelCase , dtype=torch.float) labels.append(_UpperCAmelCase) __A : str = labels return inputs_dict def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = YolosModelTester(self) __A : Dict = ConfigTester(self , config_class=_UpperCAmelCase , has_text_modality=_UpperCAmelCase , hidden_size=37) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A ,__A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : Tuple = model_class(_UpperCAmelCase) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) __A : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase , nn.Linear)) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A ,__A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : List[Any] = model_class(_UpperCAmelCase) __A : str = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A : int = [*signature.parameters.keys()] __A : List[str] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A ,__A : Dict = self.model_tester.prepare_config_and_inputs_for_common() __A : Optional[int] = True # in YOLOS, the seq_len is different __A : Dict = self.model_tester.expected_seq_len for model_class in self.all_model_classes: __A : Dict = True __A : Dict = False __A : Union[str, Any] = True __A : Tuple = model_class(_UpperCAmelCase) model.to(_UpperCAmelCase) model.eval() with torch.no_grad(): __A : Any = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase)) __A : Union[str, Any] = outputs.attentions self.assertEqual(len(_UpperCAmelCase) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] __A : List[Any] = True __A : List[str] = model_class(_UpperCAmelCase) model.to(_UpperCAmelCase) model.eval() with torch.no_grad(): __A : List[Any] = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase)) __A : Optional[Any] = 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, seq_len, seq_len] , ) __A : str = len(_UpperCAmelCase) # Check attention is always last and order is fine __A : Dict = True __A : Dict = True __A : Dict = model_class(_UpperCAmelCase) model.to(_UpperCAmelCase) model.eval() with torch.no_grad(): __A : List[str] = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase)) __A : Union[str, Any] = 1 self.assertEqual(out_len + added_hidden_states , len(_UpperCAmelCase)) __A : Optional[Any] = outputs.attentions self.assertEqual(len(_UpperCAmelCase) , self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' def check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): __A : Tuple = model_class(_UpperCAmelCase) model.to(_UpperCAmelCase) model.eval() with torch.no_grad(): __A : List[str] = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase)) __A : Optional[Any] = outputs.hidden_states __A : List[str] = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1) self.assertEqual(len(_UpperCAmelCase) , _UpperCAmelCase) # YOLOS has a different seq_length __A : Dict = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) __A ,__A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : List[str] = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A : Optional[int] = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*_UpperCAmelCase) @slow def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : List[Any] = YolosModel.from_pretrained(_UpperCAmelCase) self.assertIsNotNone(_UpperCAmelCase) def _lowerCAmelCase ( ) -> int: __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE (unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' return AutoImageProcessor.from_pretrained('hustvl/yolos-small') if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = YolosForObjectDetection.from_pretrained('hustvl/yolos-small').to(_UpperCAmelCase) __A : Any = self.default_image_processor __A : str = prepare_img() __A : int = image_processor(images=_UpperCAmelCase , return_tensors='pt').to(_UpperCAmelCase) # forward pass with torch.no_grad(): __A : str = model(inputs.pixel_values) # verify outputs __A : Tuple = torch.Size((1, 100, 92)) self.assertEqual(outputs.logits.shape , _UpperCAmelCase) __A : Dict = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] , device=_UpperCAmelCase , ) __A : int = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] , device=_UpperCAmelCase) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _UpperCAmelCase , atol=1e-4)) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , _UpperCAmelCase , atol=1e-4)) # verify postprocessing __A : List[str] = image_processor.post_process_object_detection( _UpperCAmelCase , threshold=0.3 , target_sizes=[image.size[::-1]])[0] __A : Optional[int] = torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]).to(_UpperCAmelCase) __A : Union[str, Any] = [75, 75, 17, 63, 17] __A : Any = torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]).to(_UpperCAmelCase) self.assertEqual(len(results['scores']) , 5) self.assertTrue(torch.allclose(results['scores'] , _UpperCAmelCase , atol=1e-4)) self.assertSequenceEqual(results['labels'].tolist() , _UpperCAmelCase) self.assertTrue(torch.allclose(results['boxes'][0, :] , _UpperCAmelCase))
8
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" snake_case_ : str = '''mock-s3-bucket''' snake_case_ : str = f'''s3://{mock_bucket}''' snake_case_ : Any = extract_path_from_uri(_UpperCamelCase ) assert dataset_path.startswith('''s3://''' ) is False snake_case_ : Optional[Any] = '''./local/path''' snake_case_ : List[str] = extract_path_from_uri(_UpperCamelCase ) assert dataset_path == new_dataset_path def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : Union[str, Any] = is_remote_filesystem(_UpperCamelCase ) assert is_remote is True snake_case_ : Union[str, Any] = fsspec.filesystem('''file''' ) snake_case_ : int = is_remote_filesystem(_UpperCamelCase ) assert is_remote is False @pytest.mark.parametrize('''compression_fs_class''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : Optional[Any] = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file} snake_case_ : Optional[Any] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case_ : List[Any] = f'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_UpperCamelCase ) snake_case_ : Dict = fsspec.filesystem(compression_fs_class.protocol , fo=_UpperCamelCase ) assert isinstance(_UpperCamelCase , _UpperCamelCase ) snake_case_ : int = os.path.basename(_UpperCamelCase ) snake_case_ : Any = expected_filename[: expected_filename.rindex('''.''' )] assert fs.glob('''*''' ) == [expected_filename] with fs.open(_UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f, open(_UpperCamelCase , encoding='''utf-8''' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('''protocol''' , ['''zip''', '''gzip'''] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Union[str, Any] = {'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path} snake_case_ : Any = compressed_file_paths[protocol] snake_case_ : Any = '''dataset.jsonl''' snake_case_ : Dict = f'''{protocol}://{member_file_path}::{compressed_file_path}''' snake_case_ , *snake_case_ : Optional[Any] = fsspec.get_fs_token_paths(_UpperCamelCase ) assert fs.isfile(_UpperCamelCase ) assert not fs.isfile('''non_existing_''' + member_file_path ) @pytest.mark.integration def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : Optional[int] = hf_api.dataset_info(_UpperCamelCase , token=_UpperCamelCase ) snake_case_ : List[str] = HfFileSystem(repo_info=_UpperCamelCase , token=_UpperCamelCase ) assert sorted(hffs.glob('''*''' ) ) == [".gitattributes", "data"] assert hffs.isdir('''data''' ) assert hffs.isfile('''.gitattributes''' ) and hffs.isfile('''data/text_data.txt''' ) with open(_UpperCamelCase ) as f: assert hffs.open('''data/text_data.txt''' , '''r''' ).read() == f.read() def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Tuple = '''bz2''' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_UpperCamelCase , _UpperCamelCase , clobber=_UpperCamelCase ) with pytest.warns(_UpperCamelCase ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_UpperCamelCase ) == 1 assert ( str(warning_info[0].message ) == f'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
60
0
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE__ = '''MobileNetV1Config''' # Base docstring SCREAMING_SNAKE_CASE__ = '''google/mobilenet_v1_1.0_224''' SCREAMING_SNAKE_CASE__ = [1, 1_0_2_4, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE__ = '''google/mobilenet_v1_1.0_224''' SCREAMING_SNAKE_CASE__ = '''tabby, tabby cat''' SCREAMING_SNAKE_CASE__ = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def A ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None ) -> List[str]: A__ = {} if isinstance(__UpperCamelCase , __UpperCamelCase ): A__ = model.mobilenet_va else: A__ = model A__ = 'MobilenetV1/Conv2d_0/' A__ = backbone.conv_stem.convolution.weight A__ = backbone.conv_stem.normalization.bias A__ = backbone.conv_stem.normalization.weight A__ = backbone.conv_stem.normalization.running_mean A__ = backbone.conv_stem.normalization.running_var for i in range(13 ): A__ = i + 1 A__ = i * 2 A__ = backbone.layer[pt_index] A__ = f'''MobilenetV1/Conv2d_{tf_index}_depthwise/''' A__ = pointer.convolution.weight A__ = pointer.normalization.bias A__ = pointer.normalization.weight A__ = pointer.normalization.running_mean A__ = pointer.normalization.running_var A__ = backbone.layer[pt_index + 1] A__ = f'''MobilenetV1/Conv2d_{tf_index}_pointwise/''' A__ = pointer.convolution.weight A__ = pointer.normalization.bias A__ = pointer.normalization.weight A__ = pointer.normalization.running_mean A__ = pointer.normalization.running_var if isinstance(__UpperCamelCase , __UpperCamelCase ): A__ = 'MobilenetV1/Logits/Conv2d_1c_1x1/' A__ = model.classifier.weight A__ = model.classifier.bias return tf_to_pt_map def A ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Optional[Any]: try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model A__ = tf.train.list_variables(__UpperCamelCase ) A__ = {} for name, shape in init_vars: logger.info(f'''Loading TF weight {name} with shape {shape}''' ) A__ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase ) A__ = array # Build TF to PyTorch weights loading map A__ = _build_tf_to_pytorch_map(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) for name, pointer in tf_to_pt_map.items(): logger.info(f'''Importing {name}''' ) if name not in tf_weights: logger.info(f'''{name} not in tf pre-trained weights, skipping''' ) continue A__ = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) A__ = np.transpose(__UpperCamelCase , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer A__ = array.squeeze().transpose() else: A__ = np.transpose(__UpperCamelCase , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(f'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched''' ) logger.info(f'''Initialize PyTorch weight {name} {array.shape}''' ) A__ = torch.from_numpy(__UpperCamelCase ) tf_weights.pop(__UpperCamelCase , __UpperCamelCase ) tf_weights.pop(name + '/RMSProp' , __UpperCamelCase ) tf_weights.pop(name + '/RMSProp_1' , __UpperCamelCase ) tf_weights.pop(name + '/ExponentialMovingAverage' , __UpperCamelCase ) logger.info(f'''Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}''' ) return model def A ( __UpperCamelCase , __UpperCamelCase ) -> torch.Tensor: A__ , A__ = features.shape[-2:] A__ , A__ = conv_layer.stride A__ , A__ = conv_layer.kernel_size if in_height % stride_height == 0: A__ = max(kernel_height - stride_height , 0 ) else: A__ = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: A__ = max(kernel_width - stride_width , 0 ) else: A__ = max(kernel_width - (in_width % stride_width) , 0 ) A__ = pad_along_width // 2 A__ = pad_along_width - pad_left A__ = pad_along_height // 2 A__ = pad_along_height - pad_top A__ = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(__UpperCamelCase , __UpperCamelCase , 'constant' , 0.0 ) class __lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : List[str] , _snake_case : MobileNetVaConfig , _snake_case : int , _snake_case : int , _snake_case : int , _snake_case : Optional[int] = 1 , _snake_case : Optional[int] = 1 , _snake_case : bool = False , _snake_case : Optional[bool] = True , _snake_case : Optional[bool or str] = True , ): """simple docstring""" super().__init__() A__ = config if in_channels % groups != 0: raise ValueError(F'''Input channels ({in_channels}) are not divisible by {groups} groups.''' ) if out_channels % groups != 0: raise ValueError(F'''Output channels ({out_channels}) are not divisible by {groups} groups.''' ) A__ = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) A__ = nn.Convad( in_channels=_snake_case , out_channels=_snake_case , kernel_size=_snake_case , stride=_snake_case , padding=_snake_case , groups=_snake_case , bias=_snake_case , padding_mode='zeros' , ) if use_normalization: A__ = nn.BatchNormad( num_features=_snake_case , eps=config.layer_norm_eps , momentum=0.9997 , affine=_snake_case , track_running_stats=_snake_case , ) else: A__ = None if use_activation: if isinstance(_snake_case , _snake_case ): A__ = ACTaFN[use_activation] elif isinstance(config.hidden_act , _snake_case ): A__ = ACTaFN[config.hidden_act] else: A__ = config.hidden_act else: A__ = None def _a ( self : Dict , _snake_case : torch.Tensor ): """simple docstring""" if self.config.tf_padding: A__ = apply_tf_padding(_snake_case , self.convolution ) A__ = self.convolution(_snake_case ) if self.normalization is not None: A__ = self.normalization(_snake_case ) if self.activation is not None: A__ = self.activation(_snake_case ) return features class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" A__ : Union[str, Any] = MobileNetVaConfig A__ : List[Any] = load_tf_weights_in_mobilenet_va A__ : Tuple = "mobilenet_v1" A__ : List[Any] = "pixel_values" A__ : int = False def _a ( self : Union[str, Any] , _snake_case : Union[nn.Linear, nn.Convad] ): """simple docstring""" if isinstance(_snake_case , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_snake_case , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) SCREAMING_SNAKE_CASE__ = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' SCREAMING_SNAKE_CASE__ = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , UpperCAmelCase_ , ) class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" def __init__( self : Optional[int] , _snake_case : MobileNetVaConfig , _snake_case : bool = True ): """simple docstring""" super().__init__(_snake_case ) A__ = config A__ = 32 A__ = max(int(depth * config.depth_multiplier ) , config.min_depth ) A__ = MobileNetVaConvLayer( _snake_case , in_channels=config.num_channels , out_channels=_snake_case , kernel_size=3 , stride=2 , ) A__ = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] A__ = nn.ModuleList() for i in range(13 ): A__ = out_channels if strides[i] == 2 or i == 0: depth *= 2 A__ = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _snake_case , in_channels=_snake_case , out_channels=_snake_case , kernel_size=3 , stride=strides[i] , groups=_snake_case , ) ) self.layer.append( MobileNetVaConvLayer( _snake_case , in_channels=_snake_case , out_channels=_snake_case , kernel_size=1 , ) ) A__ = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def _a ( self : List[str] , _snake_case : List[str] ): """simple docstring""" raise NotImplementedError @add_start_docstrings_to_model_forward(_snake_case ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_snake_case , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _a ( self : Optional[Any] , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[bool] = None , _snake_case : Optional[bool] = None , ): """simple docstring""" A__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) A__ = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) A__ = self.conv_stem(_snake_case ) A__ = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): A__ = layer_module(_snake_case ) if output_hidden_states: A__ = all_hidden_states + (hidden_states,) A__ = hidden_states if self.pooler is not None: A__ = torch.flatten(self.pooler(_snake_case ) , start_dim=1 ) else: A__ = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_snake_case , pooler_output=_snake_case , hidden_states=_snake_case , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCAmelCase_ , ) class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , _snake_case : MobileNetVaConfig ): """simple docstring""" super().__init__(_snake_case ) A__ = config.num_labels A__ = MobileNetVaModel(_snake_case ) A__ = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head A__ = nn.Dropout(config.classifier_dropout_prob , inplace=_snake_case ) A__ = nn.Linear(_snake_case , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_snake_case ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_snake_case , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _a ( self : Optional[Any] , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[bool] = None , _snake_case : Optional[torch.Tensor] = None , _snake_case : Optional[bool] = None , ): """simple docstring""" A__ = return_dict if return_dict is not None else self.config.use_return_dict A__ = self.mobilenet_va(_snake_case , output_hidden_states=_snake_case , return_dict=_snake_case ) A__ = outputs.pooler_output if return_dict else outputs[1] A__ = self.classifier(self.dropout(_snake_case ) ) A__ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: A__ = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): A__ = 'single_label_classification' else: A__ = 'multi_label_classification' if self.config.problem_type == "regression": A__ = MSELoss() if self.num_labels == 1: A__ = loss_fct(logits.squeeze() , labels.squeeze() ) else: A__ = loss_fct(_snake_case , _snake_case ) elif self.config.problem_type == "single_label_classification": A__ = CrossEntropyLoss() A__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": A__ = BCEWithLogitsLoss() A__ = loss_fct(_snake_case , _snake_case ) if not return_dict: A__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_snake_case , logits=_snake_case , hidden_states=outputs.hidden_states , )
9
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[Any] = '''encoder-decoder''' lowerCamelCase_ : Optional[Any] = True def __init__(self , **__magic_name__ ) -> Optional[int]: '''simple docstring''' super().__init__(**__magic_name__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" snake_case_ : Any = kwargs.pop('''encoder''' ) snake_case_ : Tuple = encoder_config.pop('''model_type''' ) snake_case_ : Union[str, Any] = kwargs.pop('''decoder''' ) snake_case_ : Union[str, Any] = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig snake_case_ : Optional[int] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : List[str] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : Any = True @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> PretrainedConfig: '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) snake_case_ : Tuple = True snake_case_ : Optional[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = copy.deepcopy(self.__dict__ ) snake_case_ : Any = self.encoder.to_dict() snake_case_ : Dict = self.decoder.to_dict() snake_case_ : Union[str, Any] = self.__class__.model_type return output
60
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = 0 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : str ): with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase = Path(_A ) / '''preprocessor_config.json''' _UpperCamelCase = Path(_A ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_A , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_A , '''w''' ) ) _UpperCamelCase = AutoImageProcessor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : Tuple ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase = Path(_A ) / '''preprocessor_config.json''' _UpperCamelCase = Path(_A ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_A , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_A , '''w''' ) ) _UpperCamelCase = AutoImageProcessor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase = CLIPConfig() # Create a dummy config file with image_proceesor_type _UpperCamelCase = Path(_A ) / '''preprocessor_config.json''' _UpperCamelCase = Path(_A ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_A , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_A , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally _UpperCamelCase = AutoImageProcessor.from_pretrained(_A ).to_dict() config_dict.pop('''image_processor_type''' ) _UpperCamelCase = CLIPImageProcessor(**_A ) # save in new folder model_config.save_pretrained(_A ) config.save_pretrained(_A ) _UpperCamelCase = AutoImageProcessor.from_pretrained(_A ) # make sure private variable is not incorrectly saved _UpperCamelCase = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase = Path(_A ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_A , '''w''' ) , ) _UpperCamelCase = AutoImageProcessor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : List[Any] ): with self.assertRaisesRegex( _A , '''clip-base is not a local folder and is not a valid model identifier''' ): _UpperCamelCase = AutoImageProcessor.from_pretrained('''clip-base''' ) def UpperCamelCase_ ( self : Dict ): with self.assertRaisesRegex( _A , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): _UpperCamelCase = AutoImageProcessor.from_pretrained(_A , revision='''aaaaaa''' ) def UpperCamelCase_ ( self : Union[str, Any] ): with self.assertRaisesRegex( _A , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): _UpperCamelCase = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def UpperCamelCase_ ( self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_A ): _UpperCamelCase = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_A ): _UpperCamelCase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_A ) _UpperCamelCase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_A ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_A ) _UpperCamelCase = AutoImageProcessor.from_pretrained(_A , trust_remote_code=_A ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def UpperCamelCase_ ( self : List[Any] ): try: AutoConfig.register('''custom''' , _A ) AutoImageProcessor.register(_A , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): AutoImageProcessor.register(_A , _A ) with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase = Path(_A ) / '''preprocessor_config.json''' _UpperCamelCase = Path(_A ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_A , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_A , '''w''' ) ) _UpperCamelCase = CustomImageProcessor.from_pretrained(_A ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_A ) _UpperCamelCase = AutoImageProcessor.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def UpperCamelCase_ ( self : Optional[Any] ): class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = True try: AutoConfig.register('''custom''' , _A ) AutoImageProcessor.register(_A , _A ) # If remote code is not set, the default is to use local _UpperCamelCase = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. _UpperCamelCase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_A ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub _UpperCamelCase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_A ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_A , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
10
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[int] = question_encoder snake_case_ : Optional[int] = generator snake_case_ : Optional[Any] = self.question_encoder def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' if os.path.isfile(__magic_name__ ): raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) snake_case_ : str = os.path.join(__magic_name__ , '''question_encoder_tokenizer''' ) snake_case_ : List[Any] = os.path.join(__magic_name__ , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(__magic_name__ ) self.generator.save_pretrained(__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> Any: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case_ : List[str] = kwargs.pop('''config''' , __magic_name__ ) if config is None: snake_case_ : int = RagConfig.from_pretrained(__magic_name__ ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=__magic_name__ , generator=__magic_name__ ) def __call__(self , *__magic_name__ , **__magic_name__ ) -> Tuple: '''simple docstring''' return self.current_tokenizer(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' return self.generator.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' return self.generator.decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.question_encoder def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.generator def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "longest" , __magic_name__ = None , __magic_name__ = True , **__magic_name__ , ) -> BatchEncoding: '''simple docstring''' warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , __magic_name__ , ) if max_length is None: snake_case_ : Dict = self.current_tokenizer.model_max_length snake_case_ : List[str] = self( __magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , max_length=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case_ : Optional[int] = self.current_tokenizer.model_max_length snake_case_ : Union[str, Any] = self( text_target=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , padding=__magic_name__ , max_length=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) snake_case_ : str = labels['''input_ids'''] return model_inputs
60
0
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class __A ( unittest.TestCase ): '''simple docstring''' def a__ (self , A , A ) -> Optional[int]: """simple docstring""" _a = jnp.ones((batch_size, length) ) / length return scores def a__ (self ) -> Tuple: """simple docstring""" _a = None _a = 20 _a = self._get_uniform_logits(batch_size=2 , length=A ) # tweak scores to not be uniform anymore _a = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch _a = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax _a = jax.nn.softmax(A , axis=-1 ) _a = FlaxTemperatureLogitsWarper(temperature=0.5 ) _a = FlaxTemperatureLogitsWarper(temperature=1.3 ) _a = jax.nn.softmax(temp_dist_warper_sharper(A , scores.copy() , cur_len=A ) , axis=-1 ) _a = jax.nn.softmax(temp_dist_warper_smoother(A , scores.copy() , cur_len=A ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1E-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1E-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def a__ (self ) -> Optional[int]: """simple docstring""" _a = None _a = 10 _a = 2 # create ramp distribution _a = np.broadcast_to(np.arange(A )[None, :] , (batch_size, vocab_size) ).copy() _a = ramp_logits[1:, : vocab_size // 2] + vocab_size _a = FlaxTopKLogitsWarper(3 ) _a = top_k_warp(A , A , cur_len=A ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case _a = 5 _a = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) _a = np.broadcast_to(np.arange(A )[None, :] , (batch_size, length) ).copy() _a = top_k_warp_safety_check(A , A , cur_len=A ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def a__ (self ) -> Tuple: """simple docstring""" _a = None _a = 10 _a = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) _a = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) _a = FlaxTopPLogitsWarper(0.8 ) _a = np.exp(top_p_warp(A , A , cur_len=A ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 _a = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(A , A , atol=1E-3 ) ) # check edge cases with negative and extreme logits _a = np.broadcast_to(np.arange(A )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme _a = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept _a = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) _a = top_p_warp(A , A , cur_len=A ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def a__ (self ) -> Tuple: """simple docstring""" _a = 20 _a = 4 _a = 0 _a = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=A ) # check that min length is applied at length 5 _a = ids_tensor((batch_size, 20) , vocab_size=20 ) _a = 5 _a = self._get_uniform_logits(A , A ) _a = min_dist_processor(A , A , cur_len=A ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 _a = self._get_uniform_logits(A , A ) _a = 15 _a = min_dist_processor(A , A , cur_len=A ) self.assertFalse(jnp.isinf(A ).any() ) def a__ (self ) -> Optional[int]: """simple docstring""" _a = 20 _a = 4 _a = 0 _a = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A ) # check that all scores are -inf except the bos_token_id score _a = ids_tensor((batch_size, 1) , vocab_size=20 ) _a = 1 _a = self._get_uniform_logits(A , A ) _a = logits_processor(A , A , cur_len=A ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 _a = 3 _a = self._get_uniform_logits(A , A ) _a = logits_processor(A , A , cur_len=A ) self.assertFalse(jnp.isinf(A ).any() ) def a__ (self ) -> Optional[int]: """simple docstring""" _a = 20 _a = 4 _a = 0 _a = 5 _a = FlaxForcedEOSTokenLogitsProcessor(max_length=A , eos_token_id=A ) # check that all scores are -inf except the eos_token_id when max_length is reached _a = ids_tensor((batch_size, 4) , vocab_size=20 ) _a = 4 _a = self._get_uniform_logits(A , A ) _a = logits_processor(A , A , cur_len=A ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached _a = 3 _a = self._get_uniform_logits(A , A ) _a = logits_processor(A , A , cur_len=A ) self.assertFalse(jnp.isinf(A ).any() ) def a__ (self ) -> List[Any]: """simple docstring""" _a = 4 _a = 10 _a = 15 _a = 2 _a = 1 _a = 15 # dummy input_ids and scores _a = ids_tensor((batch_size, sequence_length) , A ) _a = input_ids.copy() _a = self._get_uniform_logits(A , A ) _a = scores.copy() # instantiate all dist processors _a = FlaxTemperatureLogitsWarper(temperature=0.5 ) _a = FlaxTopKLogitsWarper(3 ) _a = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors _a = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=A ) _a = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A ) _a = FlaxForcedEOSTokenLogitsProcessor(max_length=A , eos_token_id=A ) _a = 10 # no processor list _a = temp_dist_warp(A , A , cur_len=A ) _a = top_k_warp(A , A , cur_len=A ) _a = top_p_warp(A , A , cur_len=A ) _a = min_dist_proc(A , A , cur_len=A ) _a = bos_dist_proc(A , A , cur_len=A ) _a = eos_dist_proc(A , A , cur_len=A ) # with processor list _a = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) _a = processor(A , A , cur_len=A ) # scores should be equal self.assertTrue(jnp.allclose(A , A , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def a__ (self ) -> Optional[int]: """simple docstring""" _a = 4 _a = 10 _a = 15 _a = 2 _a = 1 _a = 15 # dummy input_ids and scores _a = ids_tensor((batch_size, sequence_length) , A ) _a = input_ids.copy() _a = self._get_uniform_logits(A , A ) _a = scores.copy() # instantiate all dist processors _a = FlaxTemperatureLogitsWarper(temperature=0.5 ) _a = FlaxTopKLogitsWarper(3 ) _a = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors _a = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=A ) _a = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A ) _a = FlaxForcedEOSTokenLogitsProcessor(max_length=A , eos_token_id=A ) _a = 10 # no processor list def run_no_processor_list(A , A , A ): _a = temp_dist_warp(A , A , cur_len=A ) _a = top_k_warp(A , A , cur_len=A ) _a = top_p_warp(A , A , cur_len=A ) _a = min_dist_proc(A , A , cur_len=A ) _a = bos_dist_proc(A , A , cur_len=A ) _a = eos_dist_proc(A , A , cur_len=A ) return scores # with processor list def run_processor_list(A , A , A ): _a = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) _a = processor(A , A , cur_len=A ) return scores _a = jax.jit(A ) _a = jax.jit(A ) _a = jitted_run_no_processor_list(A , A , A ) _a = jitted_run_processor_list(A , A , A ) # scores should be equal self.assertTrue(jnp.allclose(A , A , atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
11
import inspect import unittest from transformers import ViTMSNConfig 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 ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=30 , __magic_name__=2 , __magic_name__=3 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.02 , __magic_name__=None , ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : List[Any] = image_size snake_case_ : Optional[int] = patch_size snake_case_ : Optional[Any] = num_channels snake_case_ : Optional[Any] = is_training snake_case_ : List[Any] = use_labels snake_case_ : Optional[int] = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = intermediate_size snake_case_ : Any = hidden_act snake_case_ : List[str] = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : List[str] = type_sequence_label_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ : Any = (image_size // patch_size) ** 2 snake_case_ : int = num_patches + 1 def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : List[Any] = None if self.use_labels: snake_case_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : int = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = ViTMSNModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[str] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = self.type_sequence_label_size snake_case_ : Tuple = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Any = model(__magic_name__ , labels=__magic_name__ ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ : Optional[int] = 1 snake_case_ : List[str] = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ : Any = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ : Optional[int] = config_and_inputs snake_case_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () lowerCamelCase_ : Optional[int] = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[Any] = ViTMSNModelTester(self ) snake_case_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Any = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , nn.Linear ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Tuple = model_class(__magic_name__ ) snake_case_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : Optional[int] = [*signature.parameters.keys()] snake_case_ : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : str = ViTMSNModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' torch.manual_seed(2 ) snake_case_ : List[str] = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__magic_name__ ) snake_case_ : str = self.default_image_processor snake_case_ : str = prepare_img() snake_case_ : int = image_processor(images=__magic_name__ , return_tensors='''pt''' ).to(__magic_name__ ) # forward pass with torch.no_grad(): snake_case_ : Optional[int] = model(**__magic_name__ ) # verify the logits snake_case_ : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) snake_case_ : List[Any] = torch.tensor([-0.0_803, -0.4_454, -0.2_375] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1e-4 ) )
60
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _snake_case ( unittest.TestCase ): def lowercase__ ( self): '''simple docstring''' lowercase__ : Dict = """ylacombe/bark-small""" lowercase__ : Dict = tempfile.mkdtemp() lowercase__ : Any = """en_speaker_1""" lowercase__ : Optional[int] = """This is a test string""" lowercase__ : Tuple = """speaker_embeddings_path.json""" lowercase__ : str = """speaker_embeddings""" def lowercase__ ( self , **SCREAMING_SNAKE_CASE_): '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_) def lowercase__ ( self): '''simple docstring''' shutil.rmtree(self.tmpdirname) def lowercase__ ( self): '''simple docstring''' lowercase__ : Dict = self.get_tokenizer() lowercase__ : int = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_) processor.save_pretrained(self.tmpdirname) lowercase__ : List[str] = BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def lowercase__ ( self): '''simple docstring''' lowercase__ : Union[str, Any] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowercase__ : Optional[int] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""") lowercase__ : Any = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def lowercase__ ( self): '''simple docstring''' lowercase__ : Dict = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowercase__ : Optional[int] = 35 lowercase__ : Tuple = 2 lowercase__ : Dict = 8 lowercase__ : Optional[int] = { """semantic_prompt""": np.ones(SCREAMING_SNAKE_CASE_), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len)), """fine_prompt""": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowercase__ : Tuple = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_) lowercase__ : Union[str, Any] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([])).tolist()) # test loading voice preset from npz file lowercase__ : List[Any] = os.path.join(self.tmpdirname , """file.npz""") np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_) lowercase__ : str = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_) lowercase__ : Optional[Any] = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([])).tolist()) # test loading voice preset from the hub lowercase__ : int = processor(text=self.input_string , voice_preset=self.voice_preset) def lowercase__ ( self): '''simple docstring''' lowercase__ : Dict = self.get_tokenizer() lowercase__ : str = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_) lowercase__ : List[Any] = processor(text=self.input_string) lowercase__ : List[str] = tokenizer( self.input_string , padding="""max_length""" , max_length=2_56 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
12
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = '''efficientnet''' def __init__(self , __magic_name__ = 3 , __magic_name__ = 600 , __magic_name__ = 2.0 , __magic_name__ = 3.1 , __magic_name__ = 8 , __magic_name__ = [3, 3, 5, 3, 5, 5, 3] , __magic_name__ = [32, 16, 24, 40, 80, 112, 192] , __magic_name__ = [16, 24, 40, 80, 112, 192, 320] , __magic_name__ = [] , __magic_name__ = [1, 2, 2, 2, 1, 2, 1] , __magic_name__ = [1, 2, 2, 3, 3, 4, 1] , __magic_name__ = [1, 6, 6, 6, 6, 6, 6] , __magic_name__ = 0.25 , __magic_name__ = "swish" , __magic_name__ = 2560 , __magic_name__ = "mean" , __magic_name__ = 0.02 , __magic_name__ = 0.001 , __magic_name__ = 0.99 , __magic_name__ = 0.5 , __magic_name__ = 0.2 , **__magic_name__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[str] = num_channels snake_case_ : Tuple = image_size snake_case_ : Union[str, Any] = width_coefficient snake_case_ : Tuple = depth_coefficient snake_case_ : Optional[Any] = depth_divisor snake_case_ : Optional[int] = kernel_sizes snake_case_ : str = in_channels snake_case_ : Optional[Any] = out_channels snake_case_ : int = depthwise_padding snake_case_ : Optional[Any] = strides snake_case_ : Any = num_block_repeats snake_case_ : Optional[Any] = expand_ratios snake_case_ : Union[str, Any] = squeeze_expansion_ratio snake_case_ : Union[str, Any] = hidden_act snake_case_ : Union[str, Any] = hidden_dim snake_case_ : Any = pooling_type snake_case_ : List[str] = initializer_range snake_case_ : str = batch_norm_eps snake_case_ : Optional[int] = batch_norm_momentum snake_case_ : Optional[Any] = dropout_rate snake_case_ : List[str] = drop_connect_rate snake_case_ : Union[str, Any] = sum(__magic_name__ ) * 4 class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = version.parse('''1.11''' ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-5
60
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : List[str] = {"""configuration_sew""": ["""SEW_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SEWConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Any = [ """SEW_PRETRAINED_MODEL_ARCHIVE_LIST""", """SEWForCTC""", """SEWForSequenceClassification""", """SEWModel""", """SEWPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys A__ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
13
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) lowerCAmelCase_ = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser( description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)''' ) parser.add_argument( '''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.''' ) parser.add_argument( '''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.''' ) parser.add_argument('''--vocab_size''', default=3_0_5_2_2, type=int) lowerCAmelCase_ = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, '''rb''') as fp: lowerCAmelCase_ = pickle.load(fp) logger.info('''Counting occurrences for MLM.''') lowerCAmelCase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase_ = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase_ = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, '''wb''') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
60
0
# flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter a__ = logging.get_logger(__name__) a__ = {} a__ = {} a__ = {} def __UpperCAmelCase ( __a : type ,__a : Optional[str] ,__a : Optional[List[str]] = None ,) -> Any: """simple docstring""" _a : Any = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( F"""Overwriting format type '{format_type}' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})""" ) _a : Optional[Any] = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( F"""Overwriting format type alias '{alias}' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})""" ) _a : Optional[int] = format_type def __UpperCAmelCase ( __a : Exception ,__a : Optional[str] ,__a : Optional[List[str]] = None ) -> str: """simple docstring""" _a : List[str] = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): _a : int = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=['''python''']) _register_formatter(ArrowFormatter, '''arrow''', aliases=['''pa''', '''pyarrow''']) _register_formatter(NumpyFormatter, '''numpy''', aliases=['''np''']) _register_formatter(PandasFormatter, '''pandas''', aliases=['''pd''']) _register_formatter(CustomFormatter, '''custom''') if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, '''torch''', aliases=['''pt''', '''pytorch''']) else: a__ = ValueError('''PyTorch needs to be installed to be able to return PyTorch tensors.''') _register_unavailable_formatter(_torch_error, '''torch''', aliases=['''pt''', '''pytorch''']) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, '''tensorflow''', aliases=['''tf''']) else: a__ = ValueError('''Tensorflow needs to be installed to be able to return Tensorflow tensors.''') _register_unavailable_formatter(_tf_error, '''tensorflow''', aliases=['''tf''']) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, '''jax''', aliases=[]) else: a__ = ValueError('''JAX needs to be installed to be able to return JAX arrays.''') _register_unavailable_formatter(_jax_error, '''jax''', aliases=[]) def __UpperCAmelCase ( __a : Optional[str] ) -> Optional[str]: """simple docstring""" if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def __UpperCAmelCase ( __a : Optional[str] ,**__a : Optional[Any] ) -> Formatter: """simple docstring""" _a : str = get_format_type_from_alias(__a ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**__a ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( F"""Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got '{format_type}'""" )
14
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ = "▁" , __magic_name__ = True , __magic_name__ = "<unk>" , __magic_name__ = "</s>" , __magic_name__ = "<pad>" , ) -> Dict: '''simple docstring''' snake_case_ : List[Any] = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } snake_case_ : List[str] = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): snake_case_ : int = token_dict['''token'''] snake_case_ : Optional[int] = Tokenizer(Unigram() ) snake_case_ : int = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) snake_case_ : Optional[int] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ), pre_tokenizers.Digits(individual_digits=__magic_name__ ), pre_tokenizers.Punctuation(), ] ) snake_case_ : Tuple = decoders.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ) snake_case_ : Optional[Any] = TemplateProcessing( single=F'''$A {self.special_tokens["eos"]["token"]}''' , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) snake_case_ : Optional[Any] = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) if isinstance(__magic_name__ , __magic_name__ ): snake_case_ : Dict = [files] self._tokenizer.train(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> int: '''simple docstring''' snake_case_ : Any = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) self._tokenizer.train_from_iterator(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = json.loads(self._tokenizer.to_str() ) snake_case_ : Union[str, Any] = self.special_tokens['''unk''']['''id'''] snake_case_ : Tuple = Tokenizer.from_str(json.dumps(__magic_name__ ) )
60
0
import socket def UpperCamelCase ( ) -> Union[str, Any]: """simple docstring""" lowercase__ = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) lowercase__ = socket.gethostname() lowercase__ = 1_2312 sock.connect((host, port) ) sock.send(B"""Hello server!""" ) with open("""Received_file""" , """wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: lowercase__ = sock.recv(1024 ) if not data: break out_file.write(__magic_name__ ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
15
# 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 lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : List[Any] = [False] * len(_UpperCamelCase ) snake_case_ : int = [-1] * len(_UpperCamelCase ) def dfs(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Dict = True snake_case_ : Dict = 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 lowerCAmelCase_ = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
60
0
def __a ( A__ : int ): if not isinstance(A__ , A__ ): raise ValueError("Input must be an integer" ) if input_num <= 0: raise ValueError("Input must be positive" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
16
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=False , ) -> int: '''simple docstring''' snake_case_ : int = size if size is not None else {'''height''': 20, '''width''': 20} snake_case_ : int = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} snake_case_ : str = parent snake_case_ : Optional[int] = batch_size snake_case_ : Dict = num_channels snake_case_ : List[Any] = image_size snake_case_ : Union[str, Any] = min_resolution snake_case_ : Tuple = max_resolution snake_case_ : str = do_resize snake_case_ : Tuple = size snake_case_ : int = do_center_crop snake_case_ : Tuple = crop_size snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean snake_case_ : List[str] = image_std snake_case_ : str = do_reduce_labels def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : Any = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Union[str, Any] = Image.open(dataset[0]['''file'''] ) snake_case_ : str = Image.open(dataset[1]['''file'''] ) return image, map def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : str = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Optional[Any] = Image.open(ds[0]['''file'''] ) snake_case_ : Optional[Any] = Image.open(ds[1]['''file'''] ) snake_case_ : List[str] = Image.open(ds[2]['''file'''] ) snake_case_ : str = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = BeitImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : int = BeitImageProcessingTester(self ) @property def lowerCamelCase (self ) -> str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_normalize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_mean''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_std''' ) ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) snake_case_ : Union[str, Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__magic_name__ ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' pass def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Optional[int] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : List[str] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) snake_case_ : Union[str, Any] = [] for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input snake_case_ : List[str] = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test not batched input (PIL images) snake_case_ , snake_case_ : Optional[int] = prepare_semantic_single_inputs() snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched input (PIL images) snake_case_ , snake_case_ : Dict = prepare_semantic_batch_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 snake_case_ , snake_case_ : Tuple = prepare_semantic_single_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 150 ) snake_case_ : List[Any] = True snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 )
60
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase_ : Any = { '''configuration_data2vec_audio''': ['''DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecAudioConfig'''], '''configuration_data2vec_text''': [ '''DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecTextConfig''', '''Data2VecTextOnnxConfig''', ], '''configuration_data2vec_vision''': [ '''DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Data2VecVisionConfig''', '''Data2VecVisionOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ '''DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecAudioForAudioFrameClassification''', '''Data2VecAudioForCTC''', '''Data2VecAudioForSequenceClassification''', '''Data2VecAudioForXVector''', '''Data2VecAudioModel''', '''Data2VecAudioPreTrainedModel''', ] UpperCAmelCase_ : List[Any] = [ '''DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecTextForCausalLM''', '''Data2VecTextForMaskedLM''', '''Data2VecTextForMultipleChoice''', '''Data2VecTextForQuestionAnswering''', '''Data2VecTextForSequenceClassification''', '''Data2VecTextForTokenClassification''', '''Data2VecTextModel''', '''Data2VecTextPreTrainedModel''', ] UpperCAmelCase_ : List[str] = [ '''DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Data2VecVisionForImageClassification''', '''Data2VecVisionForMaskedImageModeling''', '''Data2VecVisionForSemanticSegmentation''', '''Data2VecVisionModel''', '''Data2VecVisionPreTrainedModel''', ] if is_tf_available(): UpperCAmelCase_ : int = [ '''TFData2VecVisionForImageClassification''', '''TFData2VecVisionForSemanticSegmentation''', '''TFData2VecVisionModel''', '''TFData2VecVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys UpperCAmelCase_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
17
from sklearn.metrics import mean_squared_error import datasets lowerCAmelCase_ = '''\ @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} } ''' lowerCAmelCase_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' lowerCAmelCase_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__="uniform_average" , __magic_name__=True ) -> Any: '''simple docstring''' snake_case_ : List[Any] = mean_squared_error( __magic_name__ , __magic_name__ , sample_weight=__magic_name__ , multioutput=__magic_name__ , squared=__magic_name__ ) return {"mse": mse}
60
0
'''simple docstring''' import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def __a(SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] ): '''simple docstring''' _lowerCAmelCase = checkpoint _lowerCAmelCase = {} _lowerCAmelCase = vae_state_dict["encoder.conv_in.weight"] _lowerCAmelCase = vae_state_dict["encoder.conv_in.bias"] _lowerCAmelCase = vae_state_dict["encoder.conv_out.weight"] _lowerCAmelCase = vae_state_dict["encoder.conv_out.bias"] _lowerCAmelCase = vae_state_dict["encoder.norm_out.weight"] _lowerCAmelCase = vae_state_dict["encoder.norm_out.bias"] _lowerCAmelCase = vae_state_dict["decoder.conv_in.weight"] _lowerCAmelCase = vae_state_dict["decoder.conv_in.bias"] _lowerCAmelCase = vae_state_dict["decoder.conv_out.weight"] _lowerCAmelCase = vae_state_dict["decoder.conv_out.bias"] _lowerCAmelCase = vae_state_dict["decoder.norm_out.weight"] _lowerCAmelCase = vae_state_dict["decoder.norm_out.bias"] _lowerCAmelCase = vae_state_dict["quant_conv.weight"] _lowerCAmelCase = vae_state_dict["quant_conv.bias"] _lowerCAmelCase = vae_state_dict["post_quant_conv.weight"] _lowerCAmelCase = vae_state_dict["post_quant_conv.bias"] # Retrieves the keys for the encoder down blocks only _lowerCAmelCase = len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "encoder.down" in layer} ) _lowerCAmelCase = { layer_id: [key for key in vae_state_dict if F'''down.{layer_id}''' in key] for layer_id in range(SCREAMING_SNAKE_CASE_ ) } # Retrieves the keys for the decoder up blocks only _lowerCAmelCase = len({".".join(layer.split("." )[:3] ) for layer in vae_state_dict if "decoder.up" in layer} ) _lowerCAmelCase = { layer_id: [key for key in vae_state_dict if F'''up.{layer_id}''' in key] for layer_id in range(SCREAMING_SNAKE_CASE_ ) } for i in range(SCREAMING_SNAKE_CASE_ ): _lowerCAmelCase = [key for key in down_blocks[i] if F'''down.{i}''' in key and F'''down.{i}.downsample''' not in key] if F'''encoder.down.{i}.downsample.conv.weight''' in vae_state_dict: _lowerCAmelCase = vae_state_dict.pop( F'''encoder.down.{i}.downsample.conv.weight''' ) _lowerCAmelCase = vae_state_dict.pop( F'''encoder.down.{i}.downsample.conv.bias''' ) _lowerCAmelCase = renew_vae_resnet_paths(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = {"old": F'''down.{i}.block''', "new": F'''down_blocks.{i}.resnets'''} assign_to_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , additional_replacements=[meta_path] , config=SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = [key for key in vae_state_dict if "encoder.mid.block" in key] _lowerCAmelCase = 2 for i in range(1 , num_mid_res_blocks + 1 ): _lowerCAmelCase = [key for key in mid_resnets if F'''encoder.mid.block_{i}''' in key] _lowerCAmelCase = renew_vae_resnet_paths(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = {"old": F'''mid.block_{i}''', "new": F'''mid_block.resnets.{i - 1}'''} assign_to_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , additional_replacements=[meta_path] , config=SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = [key for key in vae_state_dict if "encoder.mid.attn" in key] _lowerCAmelCase = renew_vae_attention_paths(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = {"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , additional_replacements=[meta_path] , config=SCREAMING_SNAKE_CASE_ ) conv_attn_to_linear(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): _lowerCAmelCase = num_up_blocks - 1 - i _lowerCAmelCase = [ key for key in up_blocks[block_id] if F'''up.{block_id}''' in key and F'''up.{block_id}.upsample''' not in key ] if F'''decoder.up.{block_id}.upsample.conv.weight''' in vae_state_dict: _lowerCAmelCase = vae_state_dict[ F'''decoder.up.{block_id}.upsample.conv.weight''' ] _lowerCAmelCase = vae_state_dict[ F'''decoder.up.{block_id}.upsample.conv.bias''' ] _lowerCAmelCase = renew_vae_resnet_paths(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = {"old": F'''up.{block_id}.block''', "new": F'''up_blocks.{i}.resnets'''} assign_to_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , additional_replacements=[meta_path] , config=SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = [key for key in vae_state_dict if "decoder.mid.block" in key] _lowerCAmelCase = 2 for i in range(1 , num_mid_res_blocks + 1 ): _lowerCAmelCase = [key for key in mid_resnets if F'''decoder.mid.block_{i}''' in key] _lowerCAmelCase = renew_vae_resnet_paths(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = {"old": F'''mid.block_{i}''', "new": F'''mid_block.resnets.{i - 1}'''} assign_to_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , additional_replacements=[meta_path] , config=SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = [key for key in vae_state_dict if "decoder.mid.attn" in key] _lowerCAmelCase = renew_vae_attention_paths(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = {"old": "mid.attn_1", "new": "mid_block.attentions.0"} assign_to_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , additional_replacements=[meta_path] , config=SCREAMING_SNAKE_CASE_ ) conv_attn_to_linear(SCREAMING_SNAKE_CASE_ ) return new_checkpoint def __a(SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , ): '''simple docstring''' _lowerCAmelCase = requests.get( " https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml" ) _lowerCAmelCase = io.BytesIO(r.content ) _lowerCAmelCase = OmegaConf.load(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = 512 _lowerCAmelCase = "cuda" if torch.cuda.is_available() else "cpu" if checkpoint_path.endswith("safetensors" ): from safetensors import safe_open _lowerCAmelCase = {} with safe_open(SCREAMING_SNAKE_CASE_ , framework="pt" , device="cpu" ) as f: for key in f.keys(): _lowerCAmelCase = f.get_tensor(SCREAMING_SNAKE_CASE_ ) else: _lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ , map_location=SCREAMING_SNAKE_CASE_ )["state_dict"] # Convert the VAE model. _lowerCAmelCase = create_vae_diffusers_config(SCREAMING_SNAKE_CASE_ , image_size=SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = custom_convert_ldm_vae_checkpoint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = AutoencoderKL(**SCREAMING_SNAKE_CASE_ ) vae.load_state_dict(SCREAMING_SNAKE_CASE_ ) vae.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.") _SCREAMING_SNAKE_CASE = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
18
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class __lowerCAmelCase : lowerCamelCase_ : Any = None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) snake_case_ : List[Any] = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Optional[int] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : str = self.feature_extraction_class.from_json_file(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : str = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : Dict = self.feature_extraction_class.from_pretrained(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class() self.assertIsNotNone(__magic_name__ )
60
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device _a = False class _UpperCAmelCase( unittest.TestCase ): pass @slow @require_torch_gpu class _UpperCAmelCase( unittest.TestCase ): def UpperCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCamelCase = VersatileDiffusionImageVariationPipeline.from_pretrained('''shi-labs/versatile-diffusion''') pipe.to(__a) pipe.set_progress_bar_config(disable=__a) _UpperCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''') _UpperCamelCase = torch.manual_seed(0) _UpperCamelCase = pipe( image=__a , generator=__a , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images _UpperCamelCase = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) _UpperCamelCase = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
19
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : str = None @staticmethod def lowerCamelCase () -> Any: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def lowerCamelCase (cls ) -> List[Any]: '''simple docstring''' return F'''`pip install {cls.pip_package or cls.name}`''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[int] = '''optuna''' @staticmethod def lowerCamelCase () -> Union[str, Any]: '''simple docstring''' return is_optuna_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Union[str, Any]: '''simple docstring''' return run_hp_search_optuna(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_optuna(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''ray''' lowerCamelCase_ : List[str] = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase () -> List[Any]: '''simple docstring''' return is_ray_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_ray(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_ray(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''sigopt''' @staticmethod def lowerCamelCase () -> Optional[int]: '''simple docstring''' return is_sigopt_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> List[str]: '''simple docstring''' return run_hp_search_sigopt(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' return default_hp_space_sigopt(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''wandb''' @staticmethod def lowerCamelCase () -> Dict: '''simple docstring''' return is_wandb_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_wandb(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return default_hp_space_wandb(__magic_name__ ) lowerCAmelCase_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_UpperCamelCase ) > 0: snake_case_ : Dict = available_backends[0].name if len(_UpperCamelCase ) > 1: logger.info( f'''{len(_UpperCamelCase )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( f''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
60
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase: List[str] = { 'configuration_roberta': ['ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaConfig', 'RobertaOnnxConfig'], 'tokenization_roberta': ['RobertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase: int = ['RobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase: Any = [ 'ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaForCausalLM', 'RobertaForMaskedLM', 'RobertaForMultipleChoice', 'RobertaForQuestionAnswering', 'RobertaForSequenceClassification', 'RobertaForTokenClassification', 'RobertaModel', 'RobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase: Optional[int] = [ 'TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaForCausalLM', 'TFRobertaForMaskedLM', 'TFRobertaForMultipleChoice', 'TFRobertaForQuestionAnswering', 'TFRobertaForSequenceClassification', 'TFRobertaForTokenClassification', 'TFRobertaMainLayer', 'TFRobertaModel', 'TFRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase: Union[str, Any] = [ 'FlaxRobertaForCausalLM', 'FlaxRobertaForMaskedLM', 'FlaxRobertaForMultipleChoice', 'FlaxRobertaForQuestionAnswering', 'FlaxRobertaForSequenceClassification', 'FlaxRobertaForTokenClassification', 'FlaxRobertaModel', 'FlaxRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys _lowerCAmelCase: Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
20
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> list: """simple docstring""" snake_case_ : Tuple = len(_UpperCamelCase ) snake_case_ : Union[str, Any] = [[0] * n for i in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): snake_case_ : Any = y_points[i] for i in range(2 , _UpperCamelCase ): for j in range(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[int] = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
60
0
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __A ( UpperCamelCase__ , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class __A ( unittest.TestCase ): @property def A__ ( self :int ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def A__ ( self :Dict ): '''simple docstring''' __magic_name__ : int =ort.SessionOptions() __magic_name__ : int =False return options def A__ ( self :Tuple ): '''simple docstring''' __magic_name__ : Optional[Any] =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) __magic_name__ : Any =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) __magic_name__ : Union[str, Any] =OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , safety_checker=__snake_case , feature_extractor=__snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__ : Tuple ="""A red cat sitting on a park bench""" __magic_name__ : int =np.random.RandomState(0 ) __magic_name__ : List[str] =pipe( prompt=__snake_case , image=__snake_case , mask_image=__snake_case , guidance_scale=7.5 , num_inference_steps=10 , generator=__snake_case , output_type="""np""" , ) __magic_name__ : Union[str, Any] =output.images __magic_name__ : str =images[0, 2_55:2_58, 2_55:2_58, -1] assert images.shape == (1, 5_12, 5_12, 3) __magic_name__ : Tuple =np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def A__ ( self :Tuple ): '''simple docstring''' __magic_name__ : Tuple =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) __magic_name__ : Tuple =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) __magic_name__ : Optional[int] =LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-inpainting""" , subfolder="""scheduler""" , revision="""onnx""" ) __magic_name__ : Optional[Any] =OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , scheduler=__snake_case , safety_checker=__snake_case , feature_extractor=__snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__ : str ="""A red cat sitting on a park bench""" __magic_name__ : Optional[int] =np.random.RandomState(0 ) __magic_name__ : Optional[int] =pipe( prompt=__snake_case , image=__snake_case , mask_image=__snake_case , guidance_scale=7.5 , num_inference_steps=20 , generator=__snake_case , output_type="""np""" , ) __magic_name__ : Union[str, Any] =output.images __magic_name__ : Union[str, Any] =images[0, 2_55:2_58, 2_55:2_58, -1] assert images.shape == (1, 5_12, 5_12, 3) __magic_name__ : Any =np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
21
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
'''simple docstring''' # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers _snake_case : str = float('nan') class A : def __init__( self : Union[str, Any] , lowerCAmelCase_ : Optional[int] ) -> List[Any]: """simple docstring""" _a = sys.stdout _a = open(lowerCAmelCase_ , '''a''' ) def __getattr__( self : Dict , lowerCAmelCase_ : Union[str, Any] ) -> List[str]: """simple docstring""" return getattr(self.stdout , lowerCAmelCase_ ) def __lowerCAmelCase ( self : List[Any] , lowerCAmelCase_ : Optional[int] ) -> str: """simple docstring""" self.stdout.write(lowerCAmelCase_ ) # strip tqdm codes self.file.write(re.sub(R'''^.*\r''' , '''''' , lowerCAmelCase_ , 0 , re.M ) ) def snake_case_ (UpperCamelCase : List[str]=80 , UpperCamelCase : int=False ): '''simple docstring''' _a = [] # deal with critical env vars _a = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: _a = os.environ.get(UpperCamelCase , UpperCamelCase ) if val is not None: cmd.append(f'{key}={val}' ) # python executable (not always needed if the script is executable) _a = sys.executable if full_python_path else sys.executable.split('''/''' )[-1] cmd.append(UpperCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes _a = [] _a = '''''' while len(UpperCamelCase ) > 0: current_line += f'{cmd.pop(0 )} ' if len(UpperCamelCase ) == 0 or len(UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(UpperCamelCase ) _a = '''''' return "\\\n".join(UpperCamelCase ) def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : List[Any] ): '''simple docstring''' _a = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd ) # remove --output_dir if any and set our own _a = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd ) args.base_cmd += f' --output_dir {output_dir}' # ensure we have --overwrite_output_dir _a = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Any , UpperCamelCase : Union[str, Any] , UpperCamelCase : int , UpperCamelCase : Dict , UpperCamelCase : List[str] , UpperCamelCase : Any ): '''simple docstring''' if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) _a = subprocess.run(UpperCamelCase , capture_output=UpperCamelCase , text=UpperCamelCase ) if verbose: print('''STDOUT''' , result.stdout ) print('''STDERR''' , result.stderr ) # save the streams _a = variation.replace(''' ''' , '''-''' ) with open(Path(UpperCamelCase ) / f'log.{prefix}.stdout.txt' , '''w''' ) as f: f.write(result.stdout ) with open(Path(UpperCamelCase ) / f'log.{prefix}.stderr.txt' , '''w''' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('''failed''' ) return {target_metric_key: nan} with io.open(f'{output_dir}/all_results.json' , '''r''' , encoding='''utf-8''' ) as f: _a = json.load(UpperCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def snake_case_ (UpperCamelCase : List[str] , UpperCamelCase : Tuple , UpperCamelCase : Any , UpperCamelCase : str , UpperCamelCase : Dict , UpperCamelCase : Any , UpperCamelCase : str , UpperCamelCase : str , UpperCamelCase : Any , UpperCamelCase : List[str] , ): '''simple docstring''' _a = [] _a = [] _a = f'{id}: {variation:<{longest_variation_len}}' _a = f'{preamble}: ' _a = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(UpperCamelCase ) , desc=UpperCamelCase , leave=UpperCamelCase ): _a = process_run_single( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) _a = single_run_metrics[target_metric_key] if not math.isnan(UpperCamelCase ): metrics.append(UpperCamelCase ) results.append(UpperCamelCase ) outcome += "✓" else: outcome += "✘" _a = f'\33[2K\r{outcome}' if len(UpperCamelCase ) > 0: _a = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} _a = round(mean_metrics[target_metric_key] , 2 ) _a = f'{outcome} {mean_target}' if len(UpperCamelCase ) > 1: results_str += f' {tuple(round(UpperCamelCase , 2 ) for x in results )}' print(UpperCamelCase ) _a = variation return mean_metrics else: print(UpperCamelCase ) return {variation_key: variation, target_metric_key: nan} def snake_case_ (): '''simple docstring''' _a = torch.cuda.get_device_properties(torch.device('''cuda''' ) ) return f'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n' def snake_case_ (UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Dict , UpperCamelCase : Dict , UpperCamelCase : str ): '''simple docstring''' _a = pd.DataFrame(UpperCamelCase ) _a = '''variation''' _a = '''diff_%''' _a = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan _a = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(UpperCamelCase ): # as a fallback, use the minimal value as the sentinel _a = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(UpperCamelCase ): _a = df.apply( lambda UpperCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='''columns''' , ) # re-order columns _a = [variation_key, target_metric_key, diff_key, *report_metric_keys] _a = df.reindex(UpperCamelCase , axis='''columns''' ) # reorder cols # capitalize _a = df.rename(str.capitalize , axis='''columns''' ) # make the cols as narrow as possible _a = df.rename(lambda UpperCamelCase : c.replace('''_''' , '''<br>''' ) , axis='''columns''' ) _a = df.rename(lambda UpperCamelCase : c.replace('''_''' , '''\n''' ) , axis='''columns''' ) _a = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=UpperCamelCase , floatfmt='''.2f''' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=UpperCamelCase , floatfmt='''.2f''' )] print('''\n\n'''.join(UpperCamelCase ) ) def snake_case_ (): '''simple docstring''' _a = argparse.ArgumentParser() parser.add_argument( '''--base-cmd''' , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help='''Base cmd''' , ) parser.add_argument( '''--variations''' , default=UpperCamelCase , type=UpperCamelCase , nargs='''+''' , required=UpperCamelCase , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , ) parser.add_argument( '''--base-variation''' , default=UpperCamelCase , type=UpperCamelCase , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , ) parser.add_argument( '''--target-metric-key''' , default=UpperCamelCase , type=UpperCamelCase , required=UpperCamelCase , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , ) parser.add_argument( '''--report-metric-keys''' , default='''''' , type=UpperCamelCase , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , ) parser.add_argument( '''--repeat-times''' , default=1 , type=UpperCamelCase , help='''How many times to re-run each variation - an average will be reported''' , ) parser.add_argument( '''--output_dir''' , default='''output_benchmark''' , type=UpperCamelCase , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , ) parser.add_argument( '''--verbose''' , default=UpperCamelCase , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , ) _a = parser.parse_args() _a = args.output_dir Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) _a = get_base_command(UpperCamelCase , UpperCamelCase ) # split each dimension into its --foo variations _a = [list(map(str.strip , re.split(R'''\|''' , UpperCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty _a = list(map(str.strip , map(''' '''.join , itertools.product(*UpperCamelCase ) ) ) ) _a = max(len(UpperCamelCase ) for x in variations ) # split wanted keys _a = args.report_metric_keys.split() # capture prints into a log file for convenience _a = f'benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt' print(f'\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt' ) print(f'and this script\'s output is also piped into {report_fn}' ) _a = Tee(UpperCamelCase ) print(f'\n*** Running {len(UpperCamelCase )} benchmarks:' ) print(f'Base command: {" ".join(UpperCamelCase )}' ) _a = '''variation''' _a = [] for id, variation in enumerate(tqdm(UpperCamelCase , desc='''Total completion: ''' , leave=UpperCamelCase ) ): _a = base_cmd + variation.split() results.append( process_run( id + 1 , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , args.target_metric_key , UpperCamelCase , args.repeat_times , UpperCamelCase , args.verbose , ) ) process_results(UpperCamelCase , args.target_metric_key , UpperCamelCase , args.base_variation , UpperCamelCase ) if __name__ == "__main__": main()
22
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" return getitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" return setitem, k, v def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" return delitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) -> str: """simple docstring""" try: return fun(_UpperCamelCase , *_UpperCamelCase ), None except Exception as e: return None, e lowerCAmelCase_ = ( _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), ) lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_a''', '''val_b'''), ] lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), _del('''key_a'''), _del('''key_b'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), ] lowerCAmelCase_ = [ _get('''key_a'''), _del('''key_a'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), _del('''key_a'''), _get('''key_a'''), ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('''key_a''', '''val_b'''), ] @pytest.mark.parametrize( '''operations''' , ( pytest.param(_add_items , id='''add items''' ), pytest.param(_overwrite_items , id='''overwrite items''' ), pytest.param(_delete_items , id='''delete items''' ), pytest.param(_access_absent_items , id='''access absent items''' ), pytest.param(_add_with_resize_up , id='''add with resize up''' ), pytest.param(_add_with_resize_down , id='''add with resize down''' ), ) , ) def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Any = HashMap(initial_block_size=4 ) snake_case_ : Union[str, Any] = {} for _, (fun, *args) in enumerate(_UpperCamelCase ): snake_case_ , snake_case_ : str = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) assert my_res == py_res assert str(_UpperCamelCase ) == str(_UpperCamelCase ) assert set(_UpperCamelCase ) == set(_UpperCamelCase ) assert len(_UpperCamelCase ) == len(_UpperCamelCase ) assert set(my.items() ) == set(py.items() ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" def is_public(_UpperCamelCase ) -> bool: return not name.startswith('''_''' ) snake_case_ : str = {name for name in dir({} ) if is_public(_UpperCamelCase )} snake_case_ : str = {name for name in dir(HashMap() ) if is_public(_UpperCamelCase )} assert dict_public_names > hash_public_names
60
0
import logging from transformers.configuration_utils import PretrainedConfig snake_case__ : Optional[int] = logging.getLogger(__name__) class _a ( UpperCAmelCase__ ): """simple docstring""" A_ = """masked_bert""" def __init__( self , _UpperCAmelCase=30522 , _UpperCAmelCase=768 , _UpperCAmelCase=12 , _UpperCAmelCase=12 , _UpperCAmelCase=3072 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=2 , _UpperCAmelCase=0.0_2 , _UpperCAmelCase=1e-12 , _UpperCAmelCase=0 , _UpperCAmelCase="topK" , _UpperCAmelCase="constant" , _UpperCAmelCase=0.0 , **_UpperCAmelCase , ) -> Union[str, Any]: super().__init__(pad_token_id=_UpperCAmelCase , **_UpperCAmelCase ) UpperCamelCase_ = vocab_size UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = hidden_act UpperCamelCase_ = intermediate_size UpperCamelCase_ = hidden_dropout_prob UpperCamelCase_ = attention_probs_dropout_prob UpperCamelCase_ = max_position_embeddings UpperCamelCase_ = type_vocab_size UpperCamelCase_ = initializer_range UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = pruning_method UpperCamelCase_ = mask_init UpperCamelCase_ = mask_scale
23
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase ) -> list: """simple docstring""" if len(_UpperCamelCase ) == 0: return [] snake_case_ , snake_case_ : Dict = min(_UpperCamelCase ), max(_UpperCamelCase ) snake_case_ : List[str] = int(max_value - min_value ) + 1 snake_case_ : list[list] = [[] for _ in range(_UpperCamelCase )] for i in my_list: buckets[int(i - min_value )].append(_UpperCamelCase ) return [v for bucket in buckets for v in sorted(_UpperCamelCase )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -1_0, 1_5, 2, -2]) == [-1_0, -2, 0, 1, 2, 1_5]
60
0
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets UpperCAmelCase_ : Tuple = '''\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } ''' UpperCAmelCase_ : Optional[Any] = '''\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. ''' UpperCAmelCase_ : int = ''' Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for \'cvit-mkb-clsr\' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: "accuracy": Accuracy "f1": F1 score "precision": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\') # \'wnli\' or any of ["copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'precision@10\': 1.0} ''' def _UpperCamelCase (_lowerCamelCase : Optional[int] , _lowerCamelCase : List[str] )-> str: '''simple docstring''' return float((preds == labels).mean() ) def _UpperCamelCase (_lowerCamelCase : Tuple , _lowerCamelCase : List[str] )-> Tuple: '''simple docstring''' __snake_case = simple_accuracy(_lowerCamelCase , _lowerCamelCase ) __snake_case = float(fa_score(y_true=_lowerCamelCase , y_pred=_lowerCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _UpperCamelCase (_lowerCamelCase : List[Any] , _lowerCamelCase : Optional[Any] )-> str: '''simple docstring''' __snake_case = np.array(_lowerCamelCase ) __snake_case = np.array(_lowerCamelCase ) __snake_case = en_sentvecs.shape[0] # mean centering __snake_case = en_sentvecs - np.mean(_lowerCamelCase , axis=0 ) __snake_case = in_sentvecs - np.mean(_lowerCamelCase , axis=0 ) __snake_case = cdist(_lowerCamelCase , _lowerCamelCase , '''cosine''' ) __snake_case = np.array(range(_lowerCamelCase ) ) __snake_case = sim.argsort(axis=1 )[:, :10] __snake_case = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class lowerCAmelCase ( datasets.Metric): def lowerCAmelCase ( self ) -> str: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ''' '''"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ''' '''"wiki-ner"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' ) if self.config_name != '''cvit-mkb-clsr''' else datasets.Sequence(datasets.Value('''float32''' ) ), '''references''': datasets.Value('''int64''' ) if self.config_name != '''cvit-mkb-clsr''' else datasets.Sequence(datasets.Value('''float32''' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if self.config_name != '''cvit-mkb-clsr''' else None , ) def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ''' '''"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ''' '''"wiki-ner"]''' )
24
import tensorflow as tf from ...tf_utils import shape_list class __lowerCAmelCase ( tf.keras.layers.Layer ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=1 , __magic_name__=False , **__magic_name__ ) -> Dict: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[Any] = vocab_size snake_case_ : Dict = d_embed snake_case_ : Union[str, Any] = d_proj snake_case_ : str = cutoffs + [vocab_size] snake_case_ : int = [0] + self.cutoffs snake_case_ : Optional[int] = div_val snake_case_ : int = self.cutoffs[0] snake_case_ : Any = len(self.cutoffs ) - 1 snake_case_ : Union[str, Any] = self.shortlist_size + self.n_clusters snake_case_ : str = keep_order snake_case_ : int = [] snake_case_ : Union[str, Any] = [] def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' if self.n_clusters > 0: snake_case_ : Tuple = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_weight''' ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_bias''' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: snake_case_ : List[str] = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' , ) self.out_projs.append(__magic_name__ ) else: self.out_projs.append(__magic_name__ ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : List[str] = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] snake_case_ : Optional[Any] = self.d_embed // (self.div_val**i) snake_case_ : int = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' ) self.out_projs.append(__magic_name__ ) snake_case_ : int = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : Any = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) super().build(__magic_name__ ) @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = x if proj is not None: snake_case_ : List[str] = tf.einsum('''ibd,ed->ibe''' , __magic_name__ , __magic_name__ ) return tf.einsum('''ibd,nd->ibn''' , __magic_name__ , __magic_name__ ) + b @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = shape_list(__magic_name__ ) snake_case_ : Tuple = tf.range(lp_size[0] , dtype=target.dtype ) snake_case_ : Dict = tf.stack([r, target] , 1 ) return tf.gather_nd(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=True , __magic_name__=False ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = 0 if self.n_clusters == 0: snake_case_ : Any = self._logit(__magic_name__ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: snake_case_ : Union[str, Any] = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__magic_name__ , logits=__magic_name__ ) snake_case_ : Optional[Any] = tf.nn.log_softmax(__magic_name__ , axis=-1 ) else: snake_case_ : Optional[int] = shape_list(__magic_name__ ) snake_case_ : int = [] snake_case_ : List[Any] = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: snake_case_ : str = (target >= l_idx) & (target < r_idx) snake_case_ : Dict = tf.where(__magic_name__ ) snake_case_ : List[str] = tf.boolean_mask(__magic_name__ , __magic_name__ ) - l_idx if self.div_val == 1: snake_case_ : Any = self.out_layers[0][0][l_idx:r_idx] snake_case_ : Dict = self.out_layers[0][1][l_idx:r_idx] else: snake_case_ : Union[str, Any] = self.out_layers[i][0] snake_case_ : int = self.out_layers[i][1] if i == 0: snake_case_ : List[Any] = tf.concat([cur_W, self.cluster_weight] , 0 ) snake_case_ : Tuple = tf.concat([cur_b, self.cluster_bias] , 0 ) snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[0] ) snake_case_ : Any = tf.nn.log_softmax(__magic_name__ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = self._gather_logprob(__magic_name__ , __magic_name__ ) else: snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[i] ) snake_case_ : Union[str, Any] = tf.nn.log_softmax(__magic_name__ ) snake_case_ : Optional[Any] = self.cutoffs[0] + i - 1 # No probability for the head cluster snake_case_ : Optional[int] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(__magic_name__ ) if target is not None: snake_case_ : Any = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : str = self._gather_logprob(__magic_name__ , __magic_name__ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(__magic_name__ , -cur_logprob , shape_list(__magic_name__ ) ) snake_case_ : str = tf.concat(__magic_name__ , axis=-1 ) if target is not None: if return_mean: snake_case_ : int = tf.reduce_mean(__magic_name__ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(__magic_name__ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(__magic_name__ , name=self.name , aggregation='''mean''' if return_mean else '''''' ) return out
60
0
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : List[Any] = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : List[Any] = ya SCREAMING_SNAKE_CASE : str = xa for k in range(_a): SCREAMING_SNAKE_CASE : Optional[int] = y[k] + step_size * ode_func(_a , y[k]) SCREAMING_SNAKE_CASE : Union[str, Any] = y[k] + ( (step_size / 2) * (ode_func(_a , y[k]) + ode_func(x + step_size , _a)) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
25
import requests def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" snake_case_ : Tuple = {'''Content-Type''': '''application/json'''} snake_case_ : Any = requests.post(_UpperCamelCase , json={'''text''': message_body} , headers=_UpperCamelCase ) if response.status_code != 200: snake_case_ : List[Any] = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_UpperCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('''<YOUR MESSAGE BODY>''', '''<SLACK CHANNEL URL>''')
60
0
'''simple docstring''' from jiwer import compute_measures import datasets __UpperCamelCase = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n" __UpperCamelCase = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n" __UpperCamelCase = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> wer = datasets.load_metric(\"wer\")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _A ( datasets.Metric ): def lowercase__ ( self : int ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[ """https://en.wikipedia.org/wiki/Word_error_rate""", ] , ) def lowercase__ ( self : Optional[Any] , __magic_name__ : int=None , __magic_name__ : Dict=None , __magic_name__ : Union[str, Any]=False ) -> str: """simple docstring""" if concatenate_texts: return compute_measures(__magic_name__ , __magic_name__ )["wer"] else: __snake_case : Union[str, Any] = 0 __snake_case : Tuple = 0 for prediction, reference in zip(__magic_name__ , __magic_name__ ): __snake_case : Dict = compute_measures(__magic_name__ , __magic_name__ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
26
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : Optional[Any] = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class lowerCamelCase( __snake_case ): '''simple docstring''' __magic_name__ = 't5' __magic_name__ = ['past_key_values'] __magic_name__ = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self , snake_case_=3_2128 , snake_case_=512 , snake_case_=64 , snake_case_=2048 , snake_case_=6 , snake_case_=None , snake_case_=8 , snake_case_=32 , snake_case_=128 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=1.0 , snake_case_="relu" , snake_case_=True , snake_case_=True , snake_case_=0 , snake_case_=1 , **snake_case_ , ): _A = vocab_size _A = d_model _A = d_kv _A = d_ff _A = num_layers _A = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _A = num_heads _A = relative_attention_num_buckets _A = relative_attention_max_distance _A = dropout_rate _A = layer_norm_epsilon _A = initializer_factor _A = feed_forward_proj _A = use_cache _A = self.feed_forward_proj.split('-' ) _A = act_info[-1] _A = act_info[0] == 'gated' if len(snake_case_ ) > 1 and act_info[0] != "gated" or len(snake_case_ ) > 2: raise ValueError( F"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer." 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": _A = 'gelu_new' super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , is_encoder_decoder=snake_case_ , **snake_case_ , ) class lowerCamelCase( __snake_case ): '''simple docstring''' @property def lowerCAmelCase__ ( self ): _A = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: _A = 'past_encoder_sequence + sequence' _A = {0: 'batch'} _A = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: _A = {0: 'batch', 1: 'decoder_sequence'} _A = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(snake_case_ , direction='inputs' ) return common_inputs @property def lowerCAmelCase__ ( self ): return 13
27
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''', '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''', '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''owlvit_text_model''' def __init__(self , __magic_name__=4_9408 , __magic_name__=512 , __magic_name__=2048 , __magic_name__=12 , __magic_name__=8 , __magic_name__=16 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , __magic_name__=0 , __magic_name__=4_9406 , __magic_name__=4_9407 , **__magic_name__ , ) -> str: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : int = vocab_size snake_case_ : str = hidden_size snake_case_ : List[Any] = intermediate_size snake_case_ : str = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : str = hidden_act snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : Union[str, Any] = initializer_range snake_case_ : int = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : str = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit_vision_model''' def __init__(self , __magic_name__=768 , __magic_name__=3072 , __magic_name__=12 , __magic_name__=12 , __magic_name__=3 , __magic_name__=768 , __magic_name__=32 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : Union[str, Any] = intermediate_size snake_case_ : Union[str, Any] = num_hidden_layers snake_case_ : Tuple = num_attention_heads snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = image_size snake_case_ : Dict = patch_size snake_case_ : List[Any] = hidden_act snake_case_ : Tuple = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : List[str] = initializer_range snake_case_ : List[Any] = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : int = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit''' lowerCamelCase_ : Optional[int] = True def __init__(self , __magic_name__=None , __magic_name__=None , __magic_name__=512 , __magic_name__=2.6_592 , __magic_name__=True , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) if text_config is None: snake_case_ : Tuple = {} logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''' ) if vision_config is None: snake_case_ : str = {} logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''' ) snake_case_ : str = OwlViTTextConfig(**__magic_name__ ) snake_case_ : Union[str, Any] = OwlViTVisionConfig(**__magic_name__ ) snake_case_ : Any = projection_dim snake_case_ : Union[str, Any] = logit_scale_init_value snake_case_ : str = return_dict snake_case_ : Any = 1.0 @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = cls.get_config_dict(__magic_name__ , **__magic_name__ ) 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(__magic_name__ , **__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> str: '''simple docstring''' snake_case_ : Optional[int] = {} snake_case_ : Union[str, Any] = text_config snake_case_ : Optional[Any] = vision_config return cls.from_dict(__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = copy.deepcopy(self.__dict__ ) snake_case_ : List[Any] = self.text_config.to_dict() snake_case_ : List[Any] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ] ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''logits_per_image''', {0: '''batch'''}), ('''logits_per_text''', {0: '''batch'''}), ('''text_embeds''', {0: '''batch'''}), ('''image_embeds''', {0: '''batch'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-4 def lowerCamelCase (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Dict = super().generate_dummy_inputs( processor.tokenizer , batch_size=__magic_name__ , seq_length=__magic_name__ , framework=__magic_name__ ) snake_case_ : List[str] = super().generate_dummy_inputs( processor.image_processor , batch_size=__magic_name__ , framework=__magic_name__ ) return {**text_input_dict, **image_input_dict} @property def lowerCamelCase (self ) -> int: '''simple docstring''' return 14
60
0
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _a ( SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' A : Optional[Any] = VideoToVideoSDPipeline A : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'''video'''} ) - {'''image''', '''width''', '''height'''} A : Tuple = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''video'''} ) - {'''image'''} A : Optional[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} A : Optional[Any] = False # No `output_type`. A : Tuple = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def UpperCamelCase_ ( self ): '''simple docstring''' torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64), layers_per_block=2, sample_size=32, in_channels=4, out_channels=4, down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D'), up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D'), cross_attention_dim=32, attention_head_dim=4, ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler( beta_start=0.0_00_85, beta_end=0.0_12, beta_schedule='scaled_linear', clip_sample=A, set_alpha_to_one=A, ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = 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 ) SCREAMING_SNAKE_CASE : int = 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=512, ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTextModel(A ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE : List[Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def UpperCamelCase_ ( self, A, A=0 ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 3, 32, 32), rng=random.Random(A ) ).to(A ) if str(A ).startswith('mps' ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(A ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=A ).manual_seed(A ) SCREAMING_SNAKE_CASE : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'video': video, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : str = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[int] = VideoToVideoSDPipeline(**A ) SCREAMING_SNAKE_CASE : int = sd_pipe.to(A ) sd_pipe.set_progress_bar_config(disable=A ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(A ) SCREAMING_SNAKE_CASE : List[str] = 'np' SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe(**A ).frames SCREAMING_SNAKE_CASE : Tuple = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) SCREAMING_SNAKE_CASE : Dict = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available(), reason='XFormers attention is only available with CUDA and `xformers` installed', ) def UpperCamelCase_ ( self ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A, expected_max_diff=5E-3 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass def UpperCamelCase_ ( self ): '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class _a ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL', torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device='cpu' ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = torch.randn((1, 10, 3, 1_024, 576), generator=A ) SCREAMING_SNAKE_CASE : Dict = video.to('cuda' ) SCREAMING_SNAKE_CASE : Tuple = 'Spiderman is surfing' SCREAMING_SNAKE_CASE : int = pipe(A, video=A, generator=A, num_inference_steps=3, output_type='pt' ).frames SCREAMING_SNAKE_CASE : Dict = np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
28
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) lowerCamelCase_ : Union[str, Any] = ['''accelerate''', '''launch'''] lowerCamelCase_ : Tuple = Path.home() / '''.cache/huggingface/accelerate''' lowerCamelCase_ : Tuple = '''default_config.yaml''' lowerCamelCase_ : str = config_folder / config_file lowerCamelCase_ : List[Any] = config_folder / '''_default_config.yaml''' lowerCamelCase_ : Dict = Path('''tests/test_configs''' ) @classmethod def lowerCamelCase (cls ) -> Dict: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCamelCase (cls ) -> Any: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=__magic_name__ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(__magic_name__ ), self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''test-tpu''' lowerCamelCase_ : Dict = '''us-central1-a''' lowerCamelCase_ : Any = '''ls''' lowerCamelCase_ : Dict = ['''accelerate''', '''tpu-config'''] lowerCamelCase_ : Tuple = '''cd /usr/share''' lowerCamelCase_ : List[Any] = '''tests/test_samples/test_command_file.sh''' lowerCamelCase_ : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : int = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=__magic_name__ ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , )
60
0
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL A_ = logging.get_logger(__name__) def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): def constraint_to_multiple_of(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=0 ,lowerCAmelCase__=None ): lowerCamelCase_ = round(val / multiple ) * multiple if max_val is not None and x > max_val: lowerCamelCase_ = math.floor(val / multiple ) * multiple if x < min_val: lowerCamelCase_ = math.ceil(val / multiple ) * multiple return x lowerCamelCase_ = (output_size, output_size) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else output_size lowerCamelCase_ , lowerCamelCase_ = get_image_size(lowerCAmelCase__ ) lowerCamelCase_ , lowerCamelCase_ = output_size # determine new height and width lowerCamelCase_ = output_height / input_height lowerCamelCase_ = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width lowerCamelCase_ = scale_width else: # fit height lowerCamelCase_ = scale_height lowerCamelCase_ = constraint_to_multiple_of(scale_height * input_height ,multiple=lowerCAmelCase__ ) lowerCamelCase_ = constraint_to_multiple_of(scale_width * input_width ,multiple=lowerCAmelCase__ ) return (new_height, new_width) class __lowerCamelCase ( lowerCAmelCase ): a__: int = ['pixel_values'] def __init__( self , UpperCAmelCase = True , UpperCAmelCase = None , UpperCAmelCase = PILImageResampling.BILINEAR , UpperCAmelCase = False , UpperCAmelCase = 1 , UpperCAmelCase = True , UpperCAmelCase = 1 / 255 , UpperCAmelCase = True , UpperCAmelCase = None , UpperCAmelCase = None , **UpperCAmelCase , ): super().__init__(**UpperCAmelCase ) lowerCamelCase_ = size if size is not None else {'''height''': 384, '''width''': 384} lowerCamelCase_ = get_size_dict(UpperCAmelCase ) lowerCamelCase_ = do_resize lowerCamelCase_ = size lowerCamelCase_ = keep_aspect_ratio lowerCamelCase_ = ensure_multiple_of lowerCamelCase_ = resample lowerCamelCase_ = do_rescale lowerCamelCase_ = rescale_factor lowerCamelCase_ = do_normalize lowerCamelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = False , UpperCAmelCase = 1 , UpperCAmelCase = PILImageResampling.BICUBIC , UpperCAmelCase = None , **UpperCAmelCase , ): lowerCamelCase_ = get_size_dict(UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) lowerCamelCase_ = get_resize_output_image_size( UpperCAmelCase , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=UpperCAmelCase , multiple=UpperCAmelCase , ) return resize(UpperCAmelCase , size=UpperCAmelCase , resample=UpperCAmelCase , data_format=UpperCAmelCase , **UpperCAmelCase ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None , **UpperCAmelCase , ): return rescale(UpperCAmelCase , scale=UpperCAmelCase , data_format=UpperCAmelCase , **UpperCAmelCase ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None , **UpperCAmelCase , ): return normalize(UpperCAmelCase , mean=UpperCAmelCase , std=UpperCAmelCase , data_format=UpperCAmelCase , **UpperCAmelCase ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = ChannelDimension.FIRST , **UpperCAmelCase , ): lowerCamelCase_ = do_resize if do_resize is not None else self.do_resize lowerCamelCase_ = size if size is not None else self.size lowerCamelCase_ = get_size_dict(UpperCAmelCase ) lowerCamelCase_ = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio lowerCamelCase_ = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of lowerCamelCase_ = resample if resample is not None else self.resample lowerCamelCase_ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ = image_mean if image_mean is not None else self.image_mean lowerCamelCase_ = image_std if image_std is not None else self.image_std lowerCamelCase_ = make_list_of_images(UpperCAmelCase ) if not valid_images(UpperCAmelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. lowerCamelCase_ = [to_numpy_array(UpperCAmelCase ) for image in images] if do_resize: lowerCamelCase_ = [self.resize(image=UpperCAmelCase , size=UpperCAmelCase , resample=UpperCAmelCase ) for image in images] if do_rescale: lowerCamelCase_ = [self.rescale(image=UpperCAmelCase , scale=UpperCAmelCase ) for image in images] if do_normalize: lowerCamelCase_ = [self.normalize(image=UpperCAmelCase , mean=UpperCAmelCase , std=UpperCAmelCase ) for image in images] lowerCamelCase_ = [to_channel_dimension_format(UpperCAmelCase , UpperCAmelCase ) for image in images] lowerCamelCase_ = {'''pixel_values''': images} return BatchFeature(data=UpperCAmelCase , tensor_type=UpperCAmelCase ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase = None ): lowerCamelCase_ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase ) != len(UpperCAmelCase ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(UpperCAmelCase ): lowerCamelCase_ = target_sizes.numpy() lowerCamelCase_ = [] for idx in range(len(UpperCAmelCase ) ): lowerCamelCase_ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=UpperCAmelCase ) lowerCamelCase_ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase ) else: lowerCamelCase_ = logits.argmax(dim=1 ) lowerCamelCase_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
29
import warnings from ..trainer import Trainer from ..utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__=None , **__magic_name__ ) -> Dict: '''simple docstring''' warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , __magic_name__ , ) super().__init__(args=__magic_name__ , **__magic_name__ )
60
0
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType __a = None __a = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image __a = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class __a: """simple docstring""" lowerCAmelCase = True lowerCAmelCase = None # Automatically constructed lowerCAmelCase = "PIL.Image.Image" lowerCAmelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) lowerCAmelCase = field(default='''Image''' , init=_a , repr=_a ) def __call__( self ) -> Tuple: return self.pa_type def a__ ( self ,_SCREAMING_SNAKE_CASE ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): UpperCAmelCase_ : List[str] = np.array(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): return {"path": value, "bytes": None} elif isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): return {"path": None, "bytes": value} elif isinstance(_SCREAMING_SNAKE_CASE ,np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE ,PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_SCREAMING_SNAKE_CASE ) elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get('''path''' )} elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''' ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support decoding images, please install \'Pillow\'.''' ) if token_per_repo_id is None: UpperCAmelCase_ : Dict = {} UpperCAmelCase_, UpperCAmelCase_ : Union[str, Any] = value['''path'''], value['''bytes'''] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(_SCREAMING_SNAKE_CASE ): UpperCAmelCase_ : Tuple = PIL.Image.open(_SCREAMING_SNAKE_CASE ) else: UpperCAmelCase_ : Dict = path.split('''::''' )[-1] try: UpperCAmelCase_ : Optional[int] = string_to_dict(_SCREAMING_SNAKE_CASE ,config.HUB_DATASETS_URL )['''repo_id'''] UpperCAmelCase_ : Tuple = token_per_repo_id.get(_SCREAMING_SNAKE_CASE ) except ValueError: UpperCAmelCase_ : Optional[Any] = None with xopen(_SCREAMING_SNAKE_CASE ,'''rb''' ,use_auth_token=_SCREAMING_SNAKE_CASE ) as f: UpperCAmelCase_ : List[str] = BytesIO(f.read() ) UpperCAmelCase_ : Optional[Any] = PIL.Image.open(bytes_ ) else: UpperCAmelCase_ : List[Any] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def a__ ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value('''binary''' ), "path": Value('''string''' ), } ) def a__ ( self ,_SCREAMING_SNAKE_CASE ) -> pa.StructArray: if pa.types.is_string(storage.type ): UpperCAmelCase_ : Dict = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) ,type=pa.binary() ) UpperCAmelCase_ : Dict = pa.StructArray.from_arrays([bytes_array, storage] ,['''bytes''', '''path'''] ,mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ : List[str] = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) ,type=pa.string() ) UpperCAmelCase_ : Tuple = pa.StructArray.from_arrays([storage, path_array] ,['''bytes''', '''path'''] ,mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('''bytes''' ) >= 0: UpperCAmelCase_ : Dict = storage.field('''bytes''' ) else: UpperCAmelCase_ : Any = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) ,type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: UpperCAmelCase_ : int = storage.field('''path''' ) else: UpperCAmelCase_ : List[str] = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) ,type=pa.string() ) UpperCAmelCase_ : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['''bytes''', '''path'''] ,mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCAmelCase_ : Optional[Any] = pa.array( [encode_np_array(np.array(_SCREAMING_SNAKE_CASE ) )['''bytes'''] if arr is not None else None for arr in storage.to_pylist()] ,type=pa.binary() ,) UpperCAmelCase_ : Any = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) ,type=pa.string() ) UpperCAmelCase_ : Dict = pa.StructArray.from_arrays( [bytes_array, path_array] ,['''bytes''', '''path'''] ,mask=bytes_array.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE ,self.pa_type ) def a__ ( self ,_SCREAMING_SNAKE_CASE ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(_SCREAMING_SNAKE_CASE ): with xopen(_SCREAMING_SNAKE_CASE ,'''rb''' ) as f: UpperCAmelCase_ : Any = f.read() return bytes_ UpperCAmelCase_ : Union[str, Any] = pa.array( [ (path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None for x in storage.to_pylist() ] ,type=pa.binary() ,) UpperCAmelCase_ : List[str] = pa.array( [os.path.basename(_SCREAMING_SNAKE_CASE ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] ,type=pa.string() ,) UpperCAmelCase_ : Union[str, Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['''bytes''', '''path'''] ,mask=bytes_array.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE ,self.pa_type ) def lowerCamelCase__ ( ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCAmelCase_ : Optional[int] = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowerCamelCase__ ( _lowercase ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = BytesIO() if image.format in list_image_compression_formats(): UpperCAmelCase_ : int = image.format else: UpperCAmelCase_ : List[Any] = '''PNG''' if image.mode in ['''1''', '''L''', '''LA''', '''RGB''', '''RGBA'''] else '''TIFF''' image.save(_lowercase , format=_lowercase ) return buffer.getvalue() def lowerCamelCase__ ( _lowercase ): '''simple docstring''' if hasattr(_lowercase , '''filename''' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(_lowercase )} def lowerCamelCase__ ( _lowercase ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) UpperCAmelCase_ : Tuple = array.dtype UpperCAmelCase_ : List[str] = dtype.byteorder if dtype.byteorder != '''=''' else _NATIVE_BYTEORDER UpperCAmelCase_ : Dict = dtype.kind UpperCAmelCase_ : Union[str, Any] = dtype.itemsize UpperCAmelCase_ : Optional[Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCAmelCase_ : Tuple = np.dtype('''|u1''' ) if dtype_kind not in ["u", "i"]: raise TypeError( f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCAmelCase_ : Union[str, Any] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCAmelCase_ : Union[str, Any] = dtype_byteorder + dtype_kind + str(_lowercase ) UpperCAmelCase_ : str = np.dtype(_lowercase ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) UpperCAmelCase_ : Any = PIL.Image.fromarray(array.astype(_lowercase ) ) return {"path": None, "bytes": image_to_bytes(_lowercase )} def lowerCamelCase__ ( _lowercase ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if objs: UpperCAmelCase_, UpperCAmelCase_ : Tuple = first_non_null_value(_lowercase ) if isinstance(_lowercase , _lowercase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(_lowercase , np.ndarray ): UpperCAmelCase_ : Any = no_op_if_value_is_null(_lowercase ) return [obj_to_image_dict_func(_lowercase ) for obj in objs] elif isinstance(_lowercase , PIL.Image.Image ): UpperCAmelCase_ : Union[str, Any] = no_op_if_value_is_null(_lowercase ) return [obj_to_image_dict_func(_lowercase ) for obj in objs] else: return objs else: return objs
30
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" snake_case_ : str = '''mock-s3-bucket''' snake_case_ : str = f'''s3://{mock_bucket}''' snake_case_ : Any = extract_path_from_uri(_UpperCamelCase ) assert dataset_path.startswith('''s3://''' ) is False snake_case_ : Optional[Any] = '''./local/path''' snake_case_ : List[str] = extract_path_from_uri(_UpperCamelCase ) assert dataset_path == new_dataset_path def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : Union[str, Any] = is_remote_filesystem(_UpperCamelCase ) assert is_remote is True snake_case_ : Union[str, Any] = fsspec.filesystem('''file''' ) snake_case_ : int = is_remote_filesystem(_UpperCamelCase ) assert is_remote is False @pytest.mark.parametrize('''compression_fs_class''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : Optional[Any] = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file} snake_case_ : Optional[Any] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case_ : List[Any] = f'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_UpperCamelCase ) snake_case_ : Dict = fsspec.filesystem(compression_fs_class.protocol , fo=_UpperCamelCase ) assert isinstance(_UpperCamelCase , _UpperCamelCase ) snake_case_ : int = os.path.basename(_UpperCamelCase ) snake_case_ : Any = expected_filename[: expected_filename.rindex('''.''' )] assert fs.glob('''*''' ) == [expected_filename] with fs.open(_UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f, open(_UpperCamelCase , encoding='''utf-8''' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('''protocol''' , ['''zip''', '''gzip'''] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Union[str, Any] = {'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path} snake_case_ : Any = compressed_file_paths[protocol] snake_case_ : Any = '''dataset.jsonl''' snake_case_ : Dict = f'''{protocol}://{member_file_path}::{compressed_file_path}''' snake_case_ , *snake_case_ : Optional[Any] = fsspec.get_fs_token_paths(_UpperCamelCase ) assert fs.isfile(_UpperCamelCase ) assert not fs.isfile('''non_existing_''' + member_file_path ) @pytest.mark.integration def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : Optional[int] = hf_api.dataset_info(_UpperCamelCase , token=_UpperCamelCase ) snake_case_ : List[str] = HfFileSystem(repo_info=_UpperCamelCase , token=_UpperCamelCase ) assert sorted(hffs.glob('''*''' ) ) == [".gitattributes", "data"] assert hffs.isdir('''data''' ) assert hffs.isfile('''.gitattributes''' ) and hffs.isfile('''data/text_data.txt''' ) with open(_UpperCamelCase ) as f: assert hffs.open('''data/text_data.txt''' , '''r''' ).read() == f.read() def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Tuple = '''bz2''' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_UpperCamelCase , _UpperCamelCase , clobber=_UpperCamelCase ) with pytest.warns(_UpperCamelCase ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_UpperCamelCase ) == 1 assert ( str(warning_info[0].message ) == f'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
60
0
from __future__ import annotations from collections.abc import Iterator class lowerCamelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] , _lowerCAmelCase : int ): SCREAMING_SNAKE_CASE_ = value SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None class lowerCamelCase_ : '''simple docstring''' def __init__( self : int , _lowerCAmelCase : Node ): SCREAMING_SNAKE_CASE_ = tree def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : Node | None ): if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : Dict ): yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
31
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[Any] = '''encoder-decoder''' lowerCamelCase_ : Optional[Any] = True def __init__(self , **__magic_name__ ) -> Optional[int]: '''simple docstring''' super().__init__(**__magic_name__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" snake_case_ : Any = kwargs.pop('''encoder''' ) snake_case_ : Tuple = encoder_config.pop('''model_type''' ) snake_case_ : Union[str, Any] = kwargs.pop('''decoder''' ) snake_case_ : Union[str, Any] = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig snake_case_ : Optional[int] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : List[str] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : Any = True @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> PretrainedConfig: '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) snake_case_ : Tuple = True snake_case_ : Optional[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = copy.deepcopy(self.__dict__ ) snake_case_ : Any = self.encoder.to_dict() snake_case_ : Dict = self.decoder.to_dict() snake_case_ : Union[str, Any] = self.__class__.model_type return output
60
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class __UpperCamelCase ( A__ ): __A : List[Any] = """roc_bert""" def __init__( self , _UpperCamelCase=30522 , _UpperCamelCase=768 , _UpperCamelCase=12 , _UpperCamelCase=12 , _UpperCamelCase=3072 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=512 , _UpperCamelCase=2 , _UpperCamelCase=0.02 , _UpperCamelCase=1e-12 , _UpperCamelCase=True , _UpperCamelCase=0 , _UpperCamelCase="absolute" , _UpperCamelCase=None , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=768 , _UpperCamelCase=910 , _UpperCamelCase=512 , _UpperCamelCase=24858 , _UpperCamelCase=True , **_UpperCamelCase , ): _UpperCAmelCase = vocab_size _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = initializer_range _UpperCAmelCase = type_vocab_size _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = use_cache _UpperCAmelCase = enable_pronunciation _UpperCAmelCase = enable_shape _UpperCAmelCase = pronunciation_embed_dim _UpperCAmelCase = pronunciation_vocab_size _UpperCAmelCase = shape_embed_dim _UpperCAmelCase = shape_vocab_size _UpperCAmelCase = concat_input _UpperCAmelCase = position_embedding_type _UpperCAmelCase = classifier_dropout super().__init__(pad_token_id=_UpperCamelCase , **_UpperCamelCase )
32
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[int] = question_encoder snake_case_ : Optional[int] = generator snake_case_ : Optional[Any] = self.question_encoder def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' if os.path.isfile(__magic_name__ ): raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) snake_case_ : str = os.path.join(__magic_name__ , '''question_encoder_tokenizer''' ) snake_case_ : List[Any] = os.path.join(__magic_name__ , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(__magic_name__ ) self.generator.save_pretrained(__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> Any: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case_ : List[str] = kwargs.pop('''config''' , __magic_name__ ) if config is None: snake_case_ : int = RagConfig.from_pretrained(__magic_name__ ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=__magic_name__ , generator=__magic_name__ ) def __call__(self , *__magic_name__ , **__magic_name__ ) -> Tuple: '''simple docstring''' return self.current_tokenizer(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' return self.generator.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' return self.generator.decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.question_encoder def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.generator def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "longest" , __magic_name__ = None , __magic_name__ = True , **__magic_name__ , ) -> BatchEncoding: '''simple docstring''' warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , __magic_name__ , ) if max_length is None: snake_case_ : Dict = self.current_tokenizer.model_max_length snake_case_ : List[str] = self( __magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , max_length=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case_ : Optional[int] = self.current_tokenizer.model_max_length snake_case_ : Union[str, Any] = self( text_target=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , padding=__magic_name__ , max_length=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) snake_case_ : str = labels['''input_ids'''] return model_inputs
60
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase__ : Optional[int] = logging.get_logger(__name__) lowerCamelCase__ : List[str] = """▁""" lowerCamelCase__ : Optional[int] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase__ : Optional[int] = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } lowerCamelCase__ : List[Any] = { """facebook/xglm-564M""": 2_0_4_8, } class __magic_name__ (snake_case_ ): '''simple docstring''' __lowercase : Optional[Any] = VOCAB_FILES_NAMES __lowercase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP __lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase : List[Any] = ['input_ids', 'attention_mask'] def __init__( self:int , _a:List[Any] , _a:List[str]="<s>" , _a:str="</s>" , _a:int="</s>" , _a:Optional[int]="<s>" , _a:Any="<unk>" , _a:int="<pad>" , _a:Optional[Dict[str, Any]] = None , **_a:int , ): snake_case__ = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case__ = 7 snake_case__ = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] snake_case__ = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) snake_case__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) snake_case__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case__ = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case__ = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} snake_case__ = len(self.sp_model ) snake_case__ = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(_a ) snake_case__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self:Optional[int] ): snake_case__ = self.__dict__.copy() snake_case__ = None snake_case__ = self.sp_model.serialized_model_proto() return state def __setstate__( self:Optional[Any] , _a:Union[str, Any] ): snake_case__ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case__ = {} snake_case__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE__ ( self:Any , _a:List[int] , _a:Optional[List[int]] = None ): if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case__ = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def SCREAMING_SNAKE_CASE__ ( self:Dict , _a:List[int] , _a:Optional[List[int]] = None , _a:bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) def SCREAMING_SNAKE_CASE__ ( self:List[str] , _a:List[int] , _a:Optional[List[int]] = None ): snake_case__ = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def SCREAMING_SNAKE_CASE__ ( self:Tuple ): return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def SCREAMING_SNAKE_CASE__ ( self:str ): snake_case__ = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self:List[str] , _a:str ): return self.sp_model.encode(_a , out_type=_a ) def SCREAMING_SNAKE_CASE__ ( self:str , _a:Optional[Any] ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case__ = self.sp_model.PieceToId(_a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE__ ( self:Tuple , _a:List[Any] ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE__ ( self:int , _a:Any ): snake_case__ = ''''''.join(_a ).replace(_a , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self:Tuple , _a:str , _a:Optional[str] = None ): if not os.path.isdir(_a ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case__ = os.path.join( _a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , '''wb''' ) as fi: snake_case__ = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
33
import inspect import unittest from transformers import ViTMSNConfig 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 ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=30 , __magic_name__=2 , __magic_name__=3 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.02 , __magic_name__=None , ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : List[Any] = image_size snake_case_ : Optional[int] = patch_size snake_case_ : Optional[Any] = num_channels snake_case_ : Optional[Any] = is_training snake_case_ : List[Any] = use_labels snake_case_ : Optional[int] = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = intermediate_size snake_case_ : Any = hidden_act snake_case_ : List[str] = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : List[str] = type_sequence_label_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ : Any = (image_size // patch_size) ** 2 snake_case_ : int = num_patches + 1 def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : List[Any] = None if self.use_labels: snake_case_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : int = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = ViTMSNModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[str] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = self.type_sequence_label_size snake_case_ : Tuple = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Any = model(__magic_name__ , labels=__magic_name__ ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ : Optional[int] = 1 snake_case_ : List[str] = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ : Any = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ : Optional[int] = config_and_inputs snake_case_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () lowerCamelCase_ : Optional[int] = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[Any] = ViTMSNModelTester(self ) snake_case_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Any = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , nn.Linear ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Tuple = model_class(__magic_name__ ) snake_case_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : Optional[int] = [*signature.parameters.keys()] snake_case_ : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : str = ViTMSNModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' torch.manual_seed(2 ) snake_case_ : List[str] = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__magic_name__ ) snake_case_ : str = self.default_image_processor snake_case_ : str = prepare_img() snake_case_ : int = image_processor(images=__magic_name__ , return_tensors='''pt''' ).to(__magic_name__ ) # forward pass with torch.no_grad(): snake_case_ : Optional[int] = model(**__magic_name__ ) # verify the logits snake_case_ : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) snake_case_ : List[Any] = torch.tensor([-0.0_803, -0.4_454, -0.2_375] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1e-4 ) )
60
0
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE_ = {'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
34
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = '''efficientnet''' def __init__(self , __magic_name__ = 3 , __magic_name__ = 600 , __magic_name__ = 2.0 , __magic_name__ = 3.1 , __magic_name__ = 8 , __magic_name__ = [3, 3, 5, 3, 5, 5, 3] , __magic_name__ = [32, 16, 24, 40, 80, 112, 192] , __magic_name__ = [16, 24, 40, 80, 112, 192, 320] , __magic_name__ = [] , __magic_name__ = [1, 2, 2, 2, 1, 2, 1] , __magic_name__ = [1, 2, 2, 3, 3, 4, 1] , __magic_name__ = [1, 6, 6, 6, 6, 6, 6] , __magic_name__ = 0.25 , __magic_name__ = "swish" , __magic_name__ = 2560 , __magic_name__ = "mean" , __magic_name__ = 0.02 , __magic_name__ = 0.001 , __magic_name__ = 0.99 , __magic_name__ = 0.5 , __magic_name__ = 0.2 , **__magic_name__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[str] = num_channels snake_case_ : Tuple = image_size snake_case_ : Union[str, Any] = width_coefficient snake_case_ : Tuple = depth_coefficient snake_case_ : Optional[Any] = depth_divisor snake_case_ : Optional[int] = kernel_sizes snake_case_ : str = in_channels snake_case_ : Optional[Any] = out_channels snake_case_ : int = depthwise_padding snake_case_ : Optional[Any] = strides snake_case_ : Any = num_block_repeats snake_case_ : Optional[Any] = expand_ratios snake_case_ : Union[str, Any] = squeeze_expansion_ratio snake_case_ : Union[str, Any] = hidden_act snake_case_ : Union[str, Any] = hidden_dim snake_case_ : Any = pooling_type snake_case_ : List[str] = initializer_range snake_case_ : str = batch_norm_eps snake_case_ : Optional[int] = batch_norm_momentum snake_case_ : Optional[Any] = dropout_rate snake_case_ : List[str] = drop_connect_rate snake_case_ : Union[str, Any] = sum(__magic_name__ ) * 4 class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = version.parse('''1.11''' ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-5
60
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ :int = 16 a_ :Tuple = 32 def a ( A__ , A__ = 1_6 ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) SCREAMING_SNAKE_CASE__ : List[str] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(A__ ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE__ : int = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=A__ , max_length=A__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE__ : Dict = datasets.map( A__ , batched=A__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE__ : Dict = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(A__ ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE__ : Any = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE__ : Dict = 1_6 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE__ : Tuple = 8 else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None return tokenizer.pad( A__ , padding='''longest''' , max_length=A__ , pad_to_multiple_of=A__ , return_tensors='''pt''' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE__ : Tuple = DataLoader( tokenized_datasets['''train'''] , shuffle=A__ , collate_fn=A__ , batch_size=A__ ) SCREAMING_SNAKE_CASE__ : str = DataLoader( tokenized_datasets['''validation'''] , shuffle=A__ , collate_fn=A__ , batch_size=A__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a_ :Union[str, Any] = mocked_dataloaders # noqa: F811 def a ( A__ , A__ ) -> int: '''simple docstring''' if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , A__ ) == "1": SCREAMING_SNAKE_CASE__ : Optional[int] = 2 # New Code # SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(args.gradient_accumulation_steps ) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(args.local_sgd_steps ) # Initialize accelerator SCREAMING_SNAKE_CASE__ : Any = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=A__ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError('''LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)''' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE__ : Any = config['''lr'''] SCREAMING_SNAKE_CASE__ : Any = int(config['''num_epochs'''] ) SCREAMING_SNAKE_CASE__ : List[str] = int(config['''seed'''] ) SCREAMING_SNAKE_CASE__ : Dict = int(config['''batch_size'''] ) SCREAMING_SNAKE_CASE__ : Tuple = evaluate.load('''glue''' , '''mrpc''' ) set_seed(A__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = get_dataloaders(A__ , A__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE__ : str = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=A__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE__ : Optional[Any] = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE__ : Dict = AdamW(params=model.parameters() , lr=A__ ) # Instantiate scheduler SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=A__ , num_warmup_steps=1_0_0 , num_training_steps=(len(A__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = accelerator.prepare( A__ , A__ , A__ , A__ , A__ ) # Now we train the model for epoch in range(A__ ): model.train() with LocalSGD( accelerator=A__ , model=A__ , local_sgd_steps=A__ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(A__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(A__ ): SCREAMING_SNAKE_CASE__ : Any = model(**A__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.loss accelerator.backward(A__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(A__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[str] = model(**A__ ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=A__ , references=A__ , ) SCREAMING_SNAKE_CASE__ : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , A__ ) def a ( ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=A__ , default=A__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) # New Code # parser.add_argument( '''--gradient_accumulation_steps''' , type=A__ , default=1 , help='''The number of minibatches to be ran before gradients are accumulated.''' , ) parser.add_argument( '''--local_sgd_steps''' , type=A__ , default=8 , help='''Number of local SGD steps or None to disable local SGD''' ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Any = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(A__ , A__ ) if __name__ == "__main__": main()
35
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) lowerCAmelCase_ = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser( description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)''' ) parser.add_argument( '''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.''' ) parser.add_argument( '''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.''' ) parser.add_argument('''--vocab_size''', default=3_0_5_2_2, type=int) lowerCAmelCase_ = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, '''rb''') as fp: lowerCAmelCase_ = pickle.load(fp) logger.info('''Counting occurrences for MLM.''') lowerCAmelCase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase_ = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase_ = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, '''wb''') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
60
0
def lowercase ( __A : Tuple , __A : Optional[int] ) -> Optional[int]: '''simple docstring''' snake_case : List[Any] = [1] for i in range(2 , __A ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" snake_case : List[str] = [] snake_case : Optional[Any] = list(range(__A ) ) # Find permutation while factorials: snake_case : str = factorials.pop() snake_case , snake_case : str = divmod(__A , __A ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
36
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ = "▁" , __magic_name__ = True , __magic_name__ = "<unk>" , __magic_name__ = "</s>" , __magic_name__ = "<pad>" , ) -> Dict: '''simple docstring''' snake_case_ : List[Any] = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } snake_case_ : List[str] = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): snake_case_ : int = token_dict['''token'''] snake_case_ : Optional[int] = Tokenizer(Unigram() ) snake_case_ : int = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) snake_case_ : Optional[int] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ), pre_tokenizers.Digits(individual_digits=__magic_name__ ), pre_tokenizers.Punctuation(), ] ) snake_case_ : Tuple = decoders.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ) snake_case_ : Optional[Any] = TemplateProcessing( single=F'''$A {self.special_tokens["eos"]["token"]}''' , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) snake_case_ : Optional[Any] = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) if isinstance(__magic_name__ , __magic_name__ ): snake_case_ : Dict = [files] self._tokenizer.train(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> int: '''simple docstring''' snake_case_ : Any = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) self._tokenizer.train_from_iterator(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = json.loads(self._tokenizer.to_str() ) snake_case_ : Union[str, Any] = self.special_tokens['''unk''']['''id'''] snake_case_ : Tuple = Tokenizer.from_str(json.dumps(__magic_name__ ) )
60
0
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def UpperCamelCase_ ( __a ) -> Dict: if is_torch_version("<" , "2.0.0" ) or not hasattr(__a , "_dynamo" ): return False return isinstance(__a , torch._dynamo.eval_frame.OptimizedModule ) def UpperCamelCase_ ( __a , __a = True ) -> Tuple: a__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) a__ : List[Any] = is_compiled_module(__a ) if is_compiled: a__ : Optional[int] = model a__ : List[str] = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__a , __a ): a__ : int = model.module if not keep_fpaa_wrapper: a__ : Union[str, Any] = getattr(__a , "forward" ) a__ : Union[str, Any] = model.__dict__.pop("_original_forward" , __a ) if original_forward is not None: while hasattr(__a , "__wrapped__" ): a__ : int = forward.__wrapped__ if forward == original_forward: break a__ : Any = forward if getattr(__a , "_converted_to_transformer_engine" , __a ): convert_model(__a , to_transformer_engine=__a ) if is_compiled: a__ : List[str] = model a__ : Optional[int] = compiled_model return model def UpperCamelCase_ ( ) -> int: PartialState().wait_for_everyone() def UpperCamelCase_ ( __a , __a ) -> int: if PartialState().distributed_type == DistributedType.TPU: xm.save(__a , __a ) elif PartialState().local_process_index == 0: torch.save(__a , __a ) @contextmanager def UpperCamelCase_ ( **__a ) -> Optional[int]: for key, value in kwargs.items(): a__ : int = str(__a ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def UpperCamelCase_ ( __a ) -> Dict: if not hasattr(__a , "__qualname__" ) and not hasattr(__a , "__name__" ): a__ : Union[str, Any] = getattr(__a , "__class__" , __a ) if hasattr(__a , "__qualname__" ): return obj.__qualname__ if hasattr(__a , "__name__" ): return obj.__name__ return str(__a ) def UpperCamelCase_ ( __a , __a ) -> str: for key, value in source.items(): if isinstance(__a , __a ): a__ : Any = destination.setdefault(__a , {} ) merge_dicts(__a , __a ) else: a__ : List[str] = value return destination def UpperCamelCase_ ( __a = None ) -> bool: if port is None: a__ : int = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
37
# 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 lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : List[Any] = [False] * len(_UpperCamelCase ) snake_case_ : int = [-1] * len(_UpperCamelCase ) def dfs(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Dict = True snake_case_ : Dict = 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 lowerCAmelCase_ = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
60
0
'''simple docstring''' import math def UpperCamelCase__ ( __magic_name__ : float , __magic_name__ : float ) -> float: '''simple docstring''' 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 > 3_60: 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(__magic_name__ ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="malus_law")
38
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=False , ) -> int: '''simple docstring''' snake_case_ : int = size if size is not None else {'''height''': 20, '''width''': 20} snake_case_ : int = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} snake_case_ : str = parent snake_case_ : Optional[int] = batch_size snake_case_ : Dict = num_channels snake_case_ : List[Any] = image_size snake_case_ : Union[str, Any] = min_resolution snake_case_ : Tuple = max_resolution snake_case_ : str = do_resize snake_case_ : Tuple = size snake_case_ : int = do_center_crop snake_case_ : Tuple = crop_size snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean snake_case_ : List[str] = image_std snake_case_ : str = do_reduce_labels def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : Any = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Union[str, Any] = Image.open(dataset[0]['''file'''] ) snake_case_ : str = Image.open(dataset[1]['''file'''] ) return image, map def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : str = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Optional[Any] = Image.open(ds[0]['''file'''] ) snake_case_ : Optional[Any] = Image.open(ds[1]['''file'''] ) snake_case_ : List[str] = Image.open(ds[2]['''file'''] ) snake_case_ : str = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = BeitImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : int = BeitImageProcessingTester(self ) @property def lowerCamelCase (self ) -> str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_normalize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_mean''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_std''' ) ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) snake_case_ : Union[str, Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__magic_name__ ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' pass def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Optional[int] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : List[str] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) snake_case_ : Union[str, Any] = [] for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input snake_case_ : List[str] = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test not batched input (PIL images) snake_case_ , snake_case_ : Optional[int] = prepare_semantic_single_inputs() snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched input (PIL images) snake_case_ , snake_case_ : Dict = prepare_semantic_batch_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 snake_case_ , snake_case_ : Tuple = prepare_semantic_single_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 150 ) snake_case_ : List[Any] = True snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 )
60
0
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '''--original_config_file''', default=None, type=str, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--scheduler_type''', default='''pndm''', type=str, help='''Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']''', ) parser.add_argument( '''--pipeline_type''', default=None, type=str, help=( '''The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'''' '''. If `None` pipeline will be automatically inferred.''' ), ) parser.add_argument( '''--image_size''', default=None, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--prediction_type''', default=None, type=str, help=( '''The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable''' ''' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') parser.add_argument( '''--stable_unclip''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.''', ) parser.add_argument( '''--stable_unclip_prior''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.''', ) parser.add_argument( '''--clip_stats_path''', type=str, help='''Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.''', required=False, ) parser.add_argument( '''--controlnet''', action='''store_true''', default=None, help='''Set flag if this is a controlnet checkpoint.''' ) parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--vae_path''', type=str, default=None, required=False, help='''Set to a path, hub id to an already converted vae to not convert it again.''', ) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
39
from sklearn.metrics import mean_squared_error import datasets lowerCAmelCase_ = '''\ @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} } ''' lowerCAmelCase_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' lowerCAmelCase_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__="uniform_average" , __magic_name__=True ) -> Any: '''simple docstring''' snake_case_ : List[Any] = mean_squared_error( __magic_name__ , __magic_name__ , sample_weight=__magic_name__ , multioutput=__magic_name__ , squared=__magic_name__ ) return {"mse": mse}
60
0
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL __UpperCAmelCase = logging.get_logger(__name__) def UpperCamelCase ( snake_case__ : Optional[int] ) -> List[List[ImageInput]]: if isinstance(snake_case__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(snake_case__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(snake_case__ ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Tuple = ["pixel_values"] def __init__( self, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = 1 / 255, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = size if size is not None else {'shortest_edge': 256} UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_, default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = crop_size if crop_size is not None else {'height': 224, 'width': 224} UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_, param_name='crop_size' ) UpperCamelCase : Optional[int] = do_resize UpperCamelCase : Optional[Any] = size UpperCamelCase : Any = do_center_crop UpperCamelCase : Tuple = crop_size UpperCamelCase : Dict = resample UpperCamelCase : int = do_rescale UpperCamelCase : Optional[Any] = rescale_factor UpperCamelCase : List[str] = offset UpperCamelCase : int = do_normalize UpperCamelCase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase : str = image_std if image_std is not None else IMAGENET_STANDARD_STD def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> np.ndarray: UpperCamelCase : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_, default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" in size: UpperCamelCase : List[str] = get_resize_output_image_size(SCREAMING_SNAKE_CASE_, size['shortest_edge'], default_to_square=SCREAMING_SNAKE_CASE_ ) elif "height" in size and "width" in size: UpperCamelCase : Dict = (size['height'], size['width']) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_, resample=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> np.ndarray: UpperCamelCase : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(SCREAMING_SNAKE_CASE_, size=(size['height'], size['width']), data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> Optional[int]: UpperCamelCase : Tuple = image.astype(np.floataa ) if offset: UpperCamelCase : Tuple = image - (scale / 2) return rescale(SCREAMING_SNAKE_CASE_, scale=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE_, mean=SCREAMING_SNAKE_CASE_, std=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST, ) -> np.ndarray: if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) if offset and not do_rescale: raise ValueError('For offset, do_rescale must also be set to True.' ) # All transformations expect numpy arrays. UpperCamelCase : Optional[int] = to_numpy_array(SCREAMING_SNAKE_CASE_ ) if do_resize: UpperCamelCase : Dict = self.resize(image=SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_, resample=SCREAMING_SNAKE_CASE_ ) if do_center_crop: UpperCamelCase : Union[str, Any] = self.center_crop(SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_ ) if do_rescale: UpperCamelCase : Optional[Any] = self.rescale(image=SCREAMING_SNAKE_CASE_, scale=SCREAMING_SNAKE_CASE_, offset=SCREAMING_SNAKE_CASE_ ) if do_normalize: UpperCamelCase : int = self.normalize(image=SCREAMING_SNAKE_CASE_, mean=SCREAMING_SNAKE_CASE_, std=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = to_channel_dimension_format(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) return image def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST, **SCREAMING_SNAKE_CASE_, ) -> PIL.Image.Image: UpperCamelCase : Union[str, Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase : List[str] = resample if resample is not None else self.resample UpperCamelCase : int = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase : int = offset if offset is not None else self.offset UpperCamelCase : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase : Optional[Any] = image_mean if image_mean is not None else self.image_mean UpperCamelCase : Dict = image_std if image_std is not None else self.image_std UpperCamelCase : Optional[Any] = size if size is not None else self.size UpperCamelCase : Tuple = get_size_dict(SCREAMING_SNAKE_CASE_, default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = crop_size if crop_size is not None else self.crop_size UpperCamelCase : Dict = get_size_dict(SCREAMING_SNAKE_CASE_, param_name='crop_size' ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) UpperCamelCase : Tuple = make_batched(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = [ [ self._preprocess_image( image=SCREAMING_SNAKE_CASE_, do_resize=SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_, resample=SCREAMING_SNAKE_CASE_, do_center_crop=SCREAMING_SNAKE_CASE_, crop_size=SCREAMING_SNAKE_CASE_, do_rescale=SCREAMING_SNAKE_CASE_, rescale_factor=SCREAMING_SNAKE_CASE_, offset=SCREAMING_SNAKE_CASE_, do_normalize=SCREAMING_SNAKE_CASE_, image_mean=SCREAMING_SNAKE_CASE_, image_std=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, ) for img in video ] for video in videos ] UpperCamelCase : str = {'pixel_values': videos} return BatchFeature(data=SCREAMING_SNAKE_CASE_, tensor_type=SCREAMING_SNAKE_CASE_ )
40
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class __lowerCAmelCase : lowerCamelCase_ : Any = None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) snake_case_ : List[Any] = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Optional[int] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : str = self.feature_extraction_class.from_json_file(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : str = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : Dict = self.feature_extraction_class.from_pretrained(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class() self.assertIsNotNone(__magic_name__ )
60
0
'''simple docstring''' from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _A ( A__ ): """simple docstring""" if isinstance(A__ , collections.abc.Iterable ): return x return (x, x) @require_tf class lowercase_ : """simple docstring""" def SCREAMING_SNAKE_CASE ( self : int ,lowercase__ : Optional[Any] ,lowercase__ : Optional[int] ): pass def SCREAMING_SNAKE_CASE ( self : str ): pass def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): pass def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Dict ,lowercase__ : Optional[Any] ,lowercase__ : Union[str, Any] ,lowercase__ : str ,lowercase__ : Optional[int]=None ,**lowercase__ : str ): __lowercase = VisionTextDualEncoderConfig.from_vision_text_configs(lowercase__ ,lowercase__ ) __lowercase = TFVisionTextDualEncoderModel(lowercase__ ) __lowercase = model(input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ) self.assertEqual(output['''text_embeds'''].shape ,(input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape ,(pixel_values.shape[0], config.projection_dim) ) def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : List[Any] ,lowercase__ : Tuple ,lowercase__ : int ,lowercase__ : List[Any] ,lowercase__ : Optional[int]=None ,**lowercase__ : Any ): __lowercase , __lowercase = self.get_vision_text_model(lowercase__ ,lowercase__ ) __lowercase = TFVisionTextDualEncoderModel(vision_model=lowercase__ ,text_model=lowercase__ ) __lowercase = model(input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ) self.assertEqual(output['''text_embeds'''].shape ,(input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape ,(pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : str ,lowercase__ : Optional[int] ,lowercase__ : int ,lowercase__ : Optional[Any] ,lowercase__ : List[str]=None ,**lowercase__ : Any ): __lowercase , __lowercase = self.get_vision_text_model(lowercase__ ,lowercase__ ) __lowercase = {'''vision_model''': vision_model, '''text_model''': text_model} __lowercase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase__ ) __lowercase = model(input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ) self.assertEqual(output['''text_embeds'''].shape ,(input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape ,(pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Dict ,lowercase__ : str ,lowercase__ : List[str] ,lowercase__ : Tuple ,lowercase__ : Any=None ,**lowercase__ : Dict ): __lowercase , __lowercase = self.get_vision_text_model(lowercase__ ,lowercase__ ) __lowercase = TFVisionTextDualEncoderModel(vision_model=lowercase__ ,text_model=lowercase__ ) __lowercase = model(input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ) __lowercase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase__ ) __lowercase = TFVisionTextDualEncoderModel.from_pretrained(lowercase__ ) __lowercase = model(input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ) __lowercase = after_output[0].numpy() __lowercase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase__ ,1e-5 ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : int ,lowercase__ : str ,lowercase__ : List[Any] ,lowercase__ : List[str] ,lowercase__ : List[Any]=None ,**lowercase__ : List[Any] ): __lowercase , __lowercase = self.get_vision_text_model(lowercase__ ,lowercase__ ) __lowercase = TFVisionTextDualEncoderModel(vision_model=lowercase__ ,text_model=lowercase__ ) __lowercase = model( input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ,output_attentions=lowercase__ ) __lowercase = output.vision_model_output.attentions self.assertEqual(len(lowercase__ ) ,vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowercase = to_atuple(vision_model.config.image_size ) __lowercase = to_atuple(vision_model.config.patch_size ) __lowercase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowercase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] ,(vision_config.num_attention_heads, seq_len, seq_len) ) __lowercase = output.text_model_output.attentions self.assertEqual(len(lowercase__ ) ,text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] ,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) ,) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : np.ndarray ,lowercase__ : np.ndarray ,lowercase__ : float ): __lowercase = np.abs((a - b) ).max() self.assertLessEqual(lowercase__ ,lowercase__ ,F"Difference between torch and flax is {diff} (>= {tol})." ) def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ): __lowercase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = self.prepare_config_and_inputs() self.check_save_load(**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowercase__ ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase , __lowercase = self.get_pretrained_model_and_inputs() __lowercase = model_a(**lowercase__ ) __lowercase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowercase__ ) __lowercase = TFVisionTextDualEncoderModel.from_pretrained(lowercase__ ) __lowercase = model_a(**lowercase__ ) __lowercase = after_outputs[0].numpy() __lowercase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase__ ,1e-5 ) @require_tf class lowercase_ (lowerCamelCase__ , unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-vit''' ,'''hf-internal-testing/tiny-random-bert''' ) __lowercase = 1_3 __lowercase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowercase = ids_tensor([batch_size, 4] ,model.text_model.config.vocab_size ) __lowercase = random_attention_mask([batch_size, 4] ) __lowercase = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE ( self : str ,lowercase__ : Optional[Any] ,lowercase__ : Union[str, Any] ): __lowercase = TFViTModel(lowercase__ ,name='''vision_model''' ) __lowercase = TFBertModel(lowercase__ ,name='''text_model''' ) return vision_model, text_model def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = TFViTModelTester(self ) __lowercase = TFBertModelTester(self ) __lowercase = vit_model_tester.prepare_config_and_inputs() __lowercase = bert_model_tester.prepare_config_and_inputs() __lowercase , __lowercase , __lowercase = vision_config_and_inputs ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class lowercase_ (lowerCamelCase__ , unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Any ): # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's # just reinitialize it. __lowercase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( '''Rocketknight1/tiny-random-deit-tf''' ,'''hf-internal-testing/tiny-random-roberta''' ) __lowercase = 1_3 __lowercase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowercase = ids_tensor([batch_size, 4] ,model.text_model.config.vocab_size ) __lowercase = random_attention_mask([batch_size, 4] ) __lowercase = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Optional[int] ,lowercase__ : Tuple ,lowercase__ : str ,lowercase__ : str ,lowercase__ : Optional[Any]=None ,**lowercase__ : str ): __lowercase , __lowercase = self.get_vision_text_model(lowercase__ ,lowercase__ ) __lowercase = TFVisionTextDualEncoderModel(vision_model=lowercase__ ,text_model=lowercase__ ) __lowercase = model( input_ids=lowercase__ ,pixel_values=lowercase__ ,attention_mask=lowercase__ ,output_attentions=lowercase__ ) __lowercase = output.vision_model_output.attentions self.assertEqual(len(lowercase__ ) ,vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __lowercase = to_atuple(vision_model.config.image_size ) __lowercase = to_atuple(vision_model.config.patch_size ) __lowercase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowercase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] ,(vision_config.num_attention_heads, seq_len, seq_len) ) __lowercase = output.text_model_output.attentions self.assertEqual(len(lowercase__ ) ,text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] ,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) ,) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Dict ,lowercase__ : Tuple ): __lowercase = TFDeiTModel(lowercase__ ,name='''vision_model''' ) __lowercase = TFRobertaModel(lowercase__ ,name='''text_model''' ) return vision_model, text_model def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = TFDeiTModelTester(self ) __lowercase = TFRobertaModelTester(self ) __lowercase = vit_model_tester.prepare_config_and_inputs() __lowercase = bert_model_tester.prepare_config_and_inputs() __lowercase , __lowercase , __lowercase = vision_config_and_inputs ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class lowercase_ (lowerCamelCase__ , unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( '''Rocketknight1/tiny-random-clip-tf''' ,'''hf-internal-testing/tiny-random-bert''' ) __lowercase = 1_3 __lowercase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowercase = ids_tensor([batch_size, 4] ,model.text_model.config.vocab_size ) __lowercase = random_attention_mask([batch_size, 4] ) __lowercase = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : Optional[Any] ,lowercase__ : Tuple ): __lowercase = TFCLIPVisionModel(lowercase__ ,name='''vision_model''' ) __lowercase = TFBertModel(lowercase__ ,name='''text_model''' ) return vision_model, text_model def SCREAMING_SNAKE_CASE ( self : Dict ): __lowercase = TFCLIPVisionModelTester(self ) __lowercase = TFBertModelTester(self ) __lowercase = clip_model_tester.prepare_config_and_inputs() __lowercase = bert_model_tester.prepare_config_and_inputs() __lowercase , __lowercase = vision_config_and_inputs ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class lowercase_ (unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = TFVisionTextDualEncoderModel.from_pretrained( '''clip-italian/clip-italian''' ,logit_scale_init_value=1.0 ,from_pt=lowercase__ ) __lowercase = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' ) __lowercase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) __lowercase = processor( text=['''una foto di un gatto''', '''una foto di un cane'''] ,images=lowercase__ ,padding=lowercase__ ,return_tensors='''np''' ) __lowercase = model(**lowercase__ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape ,(inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape ,(inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) ,) __lowercase = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() ,lowercase__ ,atol=1e-3 ) )
41
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : str = None @staticmethod def lowerCamelCase () -> Any: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def lowerCamelCase (cls ) -> List[Any]: '''simple docstring''' return F'''`pip install {cls.pip_package or cls.name}`''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[int] = '''optuna''' @staticmethod def lowerCamelCase () -> Union[str, Any]: '''simple docstring''' return is_optuna_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Union[str, Any]: '''simple docstring''' return run_hp_search_optuna(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_optuna(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''ray''' lowerCamelCase_ : List[str] = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase () -> List[Any]: '''simple docstring''' return is_ray_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_ray(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_ray(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''sigopt''' @staticmethod def lowerCamelCase () -> Optional[int]: '''simple docstring''' return is_sigopt_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> List[str]: '''simple docstring''' return run_hp_search_sigopt(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' return default_hp_space_sigopt(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''wandb''' @staticmethod def lowerCamelCase () -> Dict: '''simple docstring''' return is_wandb_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_wandb(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return default_hp_space_wandb(__magic_name__ ) lowerCAmelCase_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_UpperCamelCase ) > 0: snake_case_ : Dict = available_backends[0].name if len(_UpperCamelCase ) > 1: logger.info( f'''{len(_UpperCamelCase )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( f''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
60
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2000 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , **SCREAMING_SNAKE_CASE_ , ) -> Union[ImagePipelineOutput, Tuple]: '''simple docstring''' lowerCamelCase_ = self.unet.config.sample_size lowerCamelCase_ = (batch_size, 3, img_size, img_size) lowerCamelCase_ = self.unet lowerCamelCase_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) * self.scheduler.init_noise_sigma lowerCamelCase_ = sample.to(self.device ) self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) self.scheduler.set_sigmas(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): lowerCamelCase_ = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = self.scheduler.step_correct(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample # prediction step lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample lowerCamelCase_ = self.scheduler.step_pred(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ ,lowerCamelCase_ = output.prev_sample, output.prev_sample_mean lowerCamelCase_ = sample_mean.clamp(0 , 1 ) lowerCamelCase_ = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
42
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> list: """simple docstring""" snake_case_ : Tuple = len(_UpperCamelCase ) snake_case_ : Union[str, Any] = [[0] * n for i in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): snake_case_ : Any = y_points[i] for i in range(2 , _UpperCamelCase ): for j in range(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[int] = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
60
0
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class _a ( UpperCamelCase__ ): def lowerCamelCase_ ( self: Dict ) -> List[str]: """simple docstring""" lowercase__ = tempfile.mkdtemp() lowercase__ = 5 # Realm tok lowercase__ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] lowercase__ = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) lowercase__ = os.path.join(UpperCamelCase_ , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) lowercase__ = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) def lowerCamelCase_ ( self: str ) -> RealmTokenizer: """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCamelCase_ ( self: Optional[int] ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCamelCase_ ( self: List[Any] ) -> List[Any]: """simple docstring""" lowercase__ = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCamelCase_ ( self: str ) -> Optional[int]: """simple docstring""" lowercase__ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCamelCase_ ( self: int ) -> Union[str, Any]: """simple docstring""" lowercase__ = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCamelCase_ , ) return block_records def lowerCamelCase_ ( self: Optional[Any] ) -> int: """simple docstring""" lowercase__ = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCamelCase_ ( self: int ) -> Dict: """simple docstring""" lowercase__ = self.get_config() lowercase__ = self.get_dummy_retriever() lowercase__ = retriever.tokenizer lowercase__ = np.array([0, 3] , dtype='''long''' ) lowercase__ = tokenizer(['''Test question'''] ).input_ids lowercase__ = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ).input_ids lowercase__ = config.reader_seq_len lowercase__ , lowercase__ , lowercase__ , lowercase__ = retriever( UpperCamelCase_ , UpperCamelCase_ , answer_ids=UpperCamelCase_ , max_length=UpperCamelCase_ , return_tensors='''np''' ) self.assertEqual(len(UpperCamelCase_ ) , 2 ) self.assertEqual(len(UpperCamelCase_ ) , 2 ) self.assertEqual(len(UpperCamelCase_ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCamelCase_ ( self: Tuple ) -> Union[str, Any]: """simple docstring""" lowercase__ = self.get_config() lowercase__ = self.get_dummy_retriever() lowercase__ = retriever.tokenizer lowercase__ = np.array([0, 3, 5] , dtype='''long''' ) lowercase__ = tokenizer(['''Test question'''] ).input_ids lowercase__ = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ).input_ids lowercase__ = config.reader_seq_len lowercase__ , lowercase__ , lowercase__ , lowercase__ = retriever( UpperCamelCase_ , UpperCamelCase_ , answer_ids=UpperCamelCase_ , max_length=UpperCamelCase_ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCamelCase_ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCamelCase_ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] ) -> Tuple: """simple docstring""" lowercase__ = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path lowercase__ = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: lowercase__ = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) lowercase__ = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
43
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = { 'facebook/xlm-roberta-xl': 'https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json', 'facebook/xlm-roberta-xxl': 'https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json', # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class UpperCAmelCase__ ( A ): lowerCAmelCase_ = 'xlm-roberta-xl' def __init__( self : str,__A : Optional[Any]=2_5_0_8_8_0,__A : str=2_5_6_0,__A : Dict=3_6,__A : int=3_2,__A : int=1_0_2_4_0,__A : Union[str, Any]="gelu",__A : Optional[Any]=0.1,__A : Tuple=0.1,__A : Any=5_1_4,__A : int=1,__A : Dict=0.02,__A : Any=1e-05,__A : str=1,__A : Optional[int]=0,__A : Tuple=2,__A : Dict="absolute",__A : Dict=True,__A : str=None,**__A : Any,): super().__init__(pad_token_id=__A,bos_token_id=__A,eos_token_id=__A,**__A ) _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : List[Any] = hidden_size _lowerCamelCase : Union[str, Any] = num_hidden_layers _lowerCamelCase : Optional[int] = num_attention_heads _lowerCamelCase : Dict = hidden_act _lowerCamelCase : Tuple = intermediate_size _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : List[Any] = max_position_embeddings _lowerCamelCase : List[Any] = type_vocab_size _lowerCamelCase : Optional[Any] = initializer_range _lowerCamelCase : str = layer_norm_eps _lowerCamelCase : Optional[int] = position_embedding_type _lowerCamelCase : int = use_cache _lowerCamelCase : str = classifier_dropout class UpperCAmelCase__ ( A ): @property def lowerCamelCase_ ( self : int ): if self.task == "multiple-choice": _lowerCamelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: _lowerCamelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
44
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" return getitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" return setitem, k, v def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" return delitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) -> str: """simple docstring""" try: return fun(_UpperCamelCase , *_UpperCamelCase ), None except Exception as e: return None, e lowerCAmelCase_ = ( _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), ) lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_a''', '''val_b'''), ] lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), _del('''key_a'''), _del('''key_b'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), ] lowerCAmelCase_ = [ _get('''key_a'''), _del('''key_a'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), _del('''key_a'''), _get('''key_a'''), ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('''key_a''', '''val_b'''), ] @pytest.mark.parametrize( '''operations''' , ( pytest.param(_add_items , id='''add items''' ), pytest.param(_overwrite_items , id='''overwrite items''' ), pytest.param(_delete_items , id='''delete items''' ), pytest.param(_access_absent_items , id='''access absent items''' ), pytest.param(_add_with_resize_up , id='''add with resize up''' ), pytest.param(_add_with_resize_down , id='''add with resize down''' ), ) , ) def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Any = HashMap(initial_block_size=4 ) snake_case_ : Union[str, Any] = {} for _, (fun, *args) in enumerate(_UpperCamelCase ): snake_case_ , snake_case_ : str = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) assert my_res == py_res assert str(_UpperCamelCase ) == str(_UpperCamelCase ) assert set(_UpperCamelCase ) == set(_UpperCamelCase ) assert len(_UpperCamelCase ) == len(_UpperCamelCase ) assert set(my.items() ) == set(py.items() ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" def is_public(_UpperCamelCase ) -> bool: return not name.startswith('''_''' ) snake_case_ : str = {name for name in dir({} ) if is_public(_UpperCamelCase )} snake_case_ : str = {name for name in dir(HashMap() ) if is_public(_UpperCamelCase )} assert dict_public_names > hash_public_names
60
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase_ ( lowercase , unittest.TestCase ): """simple docstring""" _snake_case : Any = UnCLIPImageVariationPipeline _snake_case : int = IMAGE_VARIATION_PARAMS - {"""height""", """width""", """guidance_scale"""} _snake_case : Optional[int] = IMAGE_VARIATION_BATCH_PARAMS _snake_case : List[Any] = [ """generator""", """return_dict""", """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] _snake_case : Optional[Any] = False @property def __a ( self :Optional[int] ): return 32 @property def __a ( self :Tuple ): return 32 @property def __a ( self :Tuple ): return self.time_input_dim @property def __a ( self :Any ): return self.time_input_dim * 4 @property def __a ( self :Any ): return 1_00 @property def __a ( self :str ): UpperCamelCase__ :Any = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def __a ( self :List[Any] ): torch.manual_seed(0 ) UpperCamelCase__ :List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModelWithProjection(lowerCamelCase__ ) @property def __a ( self :Tuple ): torch.manual_seed(0 ) UpperCamelCase__ :List[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(lowerCamelCase__ ) @property def __a ( self :int ): torch.manual_seed(0 ) UpperCamelCase__ :List[str] = { """clip_embeddings_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """cross_attention_dim""": self.cross_attention_dim, } UpperCamelCase__ :Optional[int] = UnCLIPTextProjModel(**lowerCamelCase__ ) return model @property def __a ( self :Any ): torch.manual_seed(0 ) UpperCamelCase__ :Optional[Any] = { """sample_size""": 32, # RGB in channels """in_channels""": 3, # Out channels is double in channels because predicts mean and variance """out_channels""": 6, """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": """identity""", } UpperCamelCase__ :str = UNetaDConditionModel(**lowerCamelCase__ ) return model @property def __a ( self :List[str] ): return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def __a ( self :Optional[Any] ): torch.manual_seed(0 ) UpperCamelCase__ :Union[str, Any] = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def __a ( self :Union[str, Any] ): # seeded differently to get different unet than `self.dummy_super_res_first` torch.manual_seed(1 ) UpperCamelCase__ :List[Any] = UNetaDModel(**self.dummy_super_res_kwargs ) return model def __a ( self :Any ): UpperCamelCase__ :List[str] = self.dummy_decoder UpperCamelCase__ :List[Any] = self.dummy_text_proj UpperCamelCase__ :str = self.dummy_text_encoder UpperCamelCase__ :Any = self.dummy_tokenizer UpperCamelCase__ :str = self.dummy_super_res_first UpperCamelCase__ :Union[str, Any] = self.dummy_super_res_last UpperCamelCase__ :List[Any] = UnCLIPScheduler( variance_type="""learned_range""" , prediction_type="""epsilon""" , num_train_timesteps=10_00 , ) UpperCamelCase__ :Any = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""epsilon""" , num_train_timesteps=10_00 , ) UpperCamelCase__ :Tuple = CLIPImageProcessor(crop_size=32 , size=32 ) UpperCamelCase__ :int = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def __a ( self :str , lowerCamelCase__ :Dict , lowerCamelCase__ :Union[str, Any]=0 , lowerCamelCase__ :Tuple=True ): UpperCamelCase__ :Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) if str(lowerCamelCase__ ).startswith("""mps""" ): UpperCamelCase__ :List[Any] = torch.manual_seed(lowerCamelCase__ ) else: UpperCamelCase__ :List[Any] = torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) if pil_image: UpperCamelCase__ :Dict = input_image * 0.5 + 0.5 UpperCamelCase__ :str = input_image.clamp(0 , 1 ) UpperCamelCase__ :Any = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ :int = DiffusionPipeline.numpy_to_pil(lowerCamelCase__ )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def __a ( self :int ): UpperCamelCase__ :List[str] = """cpu""" UpperCamelCase__ :Tuple = self.get_dummy_components() UpperCamelCase__ :List[str] = self.pipeline_class(**lowerCamelCase__ ) UpperCamelCase__ :Optional[Any] = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCamelCase__ :Tuple = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :Optional[Any] = pipe(**lowerCamelCase__ ) UpperCamelCase__ :List[Any] = output.images UpperCamelCase__ :int = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :List[str] = pipe( **lowerCamelCase__ , return_dict=lowerCamelCase__ , )[0] UpperCamelCase__ :int = image[0, -3:, -3:, -1] UpperCamelCase__ :Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase__ :Optional[int] = np.array( [ 0.9997, 0.0002, 0.9997, 0.9997, 0.9969, 0.0023, 0.9997, 0.9969, 0.9970, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __a ( self :Union[str, Any] ): UpperCamelCase__ :Dict = """cpu""" UpperCamelCase__ :Dict = self.get_dummy_components() UpperCamelCase__ :Tuple = self.pipeline_class(**lowerCamelCase__ ) UpperCamelCase__ :str = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCamelCase__ :Union[str, Any] = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :Union[str, Any] = pipe(**lowerCamelCase__ ) UpperCamelCase__ :Dict = output.images UpperCamelCase__ :Optional[int] = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :Tuple = pipe( **lowerCamelCase__ , return_dict=lowerCamelCase__ , )[0] UpperCamelCase__ :List[str] = image[0, -3:, -3:, -1] UpperCamelCase__ :Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase__ :Union[str, Any] = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __a ( self :Optional[Any] ): UpperCamelCase__ :Union[str, Any] = """cpu""" UpperCamelCase__ :Optional[Any] = self.get_dummy_components() UpperCamelCase__ :Union[str, Any] = self.pipeline_class(**lowerCamelCase__ ) UpperCamelCase__ :int = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCamelCase__ :List[str] = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :List[Any] = [ pipeline_inputs["""image"""], pipeline_inputs["""image"""], ] UpperCamelCase__ :Dict = pipe(**lowerCamelCase__ ) UpperCamelCase__ :Optional[Any] = output.images UpperCamelCase__ :Optional[int] = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :Union[str, Any] = [ tuple_pipeline_inputs["""image"""], tuple_pipeline_inputs["""image"""], ] UpperCamelCase__ :Dict = pipe( **lowerCamelCase__ , return_dict=lowerCamelCase__ , )[0] UpperCamelCase__ :Dict = image[0, -3:, -3:, -1] UpperCamelCase__ :Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) UpperCamelCase__ :List[Any] = np.array( [ 0.9997, 0.9989, 0.0008, 0.0021, 0.9960, 0.0018, 0.0014, 0.0002, 0.9933, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __a ( self :Dict ): UpperCamelCase__ :List[Any] = torch.device("""cpu""" ) class lowerCAmelCase_ : """simple docstring""" _snake_case : int = 1 UpperCamelCase__ :Union[str, Any] = self.get_dummy_components() UpperCamelCase__ :List[str] = self.pipeline_class(**lowerCamelCase__ ) UpperCamelCase__ :Dict = pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCamelCase__ :int = torch.Generator(device=lowerCamelCase__ ).manual_seed(0 ) UpperCamelCase__ :List[Any] = pipe.decoder.dtype UpperCamelCase__ :str = 1 UpperCamelCase__ :List[str] = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) UpperCamelCase__ :int = pipe.prepare_latents( lowerCamelCase__ , dtype=lowerCamelCase__ , device=lowerCamelCase__ , generator=lowerCamelCase__ , latents=lowerCamelCase__ , scheduler=DummyScheduler() ) UpperCamelCase__ :int = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) UpperCamelCase__ :Optional[int] = pipe.prepare_latents( lowerCamelCase__ , dtype=lowerCamelCase__ , device=lowerCamelCase__ , generator=lowerCamelCase__ , latents=lowerCamelCase__ , scheduler=DummyScheduler() ) UpperCamelCase__ :Any = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) UpperCamelCase__ :int = pipe( **lowerCamelCase__ , decoder_latents=lowerCamelCase__ , super_res_latents=lowerCamelCase__ ).images UpperCamelCase__ :int = self.get_dummy_inputs(lowerCamelCase__ , pil_image=lowerCamelCase__ ) # Don't pass image, instead pass embedding UpperCamelCase__ :List[Any] = pipeline_inputs.pop("""image""" ) UpperCamelCase__ :str = pipe.image_encoder(lowerCamelCase__ ).image_embeds UpperCamelCase__ :List[Any] = pipe( **lowerCamelCase__ , decoder_latents=lowerCamelCase__ , super_res_latents=lowerCamelCase__ , image_embeddings=lowerCamelCase__ , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1e-4 @skip_mps def __a ( self :Union[str, Any] ): UpperCamelCase__ :Dict = torch_device == """cpu""" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor UpperCamelCase__ :Union[str, Any] = 1e-2 self._test_attention_slicing_forward_pass( test_max_difference=lowerCamelCase__ , expected_max_diff=lowerCamelCase__ ) @skip_mps def __a ( self :Union[str, Any] ): UpperCamelCase__ :Tuple = torch_device == """cpu""" UpperCamelCase__ :Optional[int] = True UpperCamelCase__ :Union[str, Any] = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] self._test_inference_batch_single_identical( test_max_difference=lowerCamelCase__ , relax_max_difference=lowerCamelCase__ , additional_params_copy_to_batched_inputs=lowerCamelCase__ , ) def __a ( self :List[str] ): UpperCamelCase__ :Any = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes UpperCamelCase__ :List[str] = [2, 3] self._test_inference_batch_consistent( batch_sizes=lowerCamelCase__ , additional_params_copy_to_batched_inputs=lowerCamelCase__ , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=lowerCamelCase__ ) @skip_mps def __a ( self :List[str] ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def __a ( self :Dict ): return super().test_save_load_local() @skip_mps def __a ( self :Tuple ): return super().test_save_load_optional_components() @slow @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __a ( self :Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __a ( self :Tuple ): UpperCamelCase__ :str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png""" ) UpperCamelCase__ :List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/unclip/karlo_v1_alpha_cat_variation_fp16.npy""" ) UpperCamelCase__ :int = UnCLIPImageVariationPipeline.from_pretrained( """kakaobrain/karlo-v1-alpha-image-variations""" , torch_dtype=torch.floataa ) UpperCamelCase__ :Optional[int] = pipeline.to(lowerCamelCase__ ) pipeline.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCamelCase__ :Tuple = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase__ :List[str] = pipeline( lowerCamelCase__ , generator=lowerCamelCase__ , output_type="""np""" , ) UpperCamelCase__ :Union[str, Any] = output.images[0] assert image.shape == (2_56, 2_56, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ , 15 )
45
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase ) -> list: """simple docstring""" if len(_UpperCamelCase ) == 0: return [] snake_case_ , snake_case_ : Dict = min(_UpperCamelCase ), max(_UpperCamelCase ) snake_case_ : List[str] = int(max_value - min_value ) + 1 snake_case_ : list[list] = [[] for _ in range(_UpperCamelCase )] for i in my_list: buckets[int(i - min_value )].append(_UpperCamelCase ) return [v for bucket in buckets for v in sorted(_UpperCamelCase )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -1_0, 1_5, 2, -2]) == [-1_0, -2, 0, 1, 2, 1_5]
60
0
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup _lowerCAmelCase : List[str] = logging.get_logger(__name__) class A_ ( _a ): def __init__( self: List[Any] ,**__lowerCAmelCase: int ): '''simple docstring''' requires_backends(self ,["bs4"] ) super().__init__(**__lowerCAmelCase ) def _lowercase ( self: Optional[Any] ,__lowerCAmelCase: Any ): '''simple docstring''' _lowerCamelCase : str = [] _lowerCamelCase : Tuple = [] _lowerCamelCase : Any = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag _lowerCamelCase : List[str] = parent.find_all(child.name ,recursive=__lowerCAmelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCAmelCase ) else next(i for i, s in enumerate(__lowerCAmelCase ,1 ) if s is child ) ) _lowerCamelCase : List[Any] = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _lowercase ( self: List[str] ,__lowerCAmelCase: List[str] ): '''simple docstring''' _lowerCamelCase : List[Any] = BeautifulSoup(__lowerCAmelCase ,"html.parser" ) _lowerCamelCase : List[Any] = [] _lowerCamelCase : List[str] = [] _lowerCamelCase : List[Any] = [] for element in html_code.descendants: if type(__lowerCAmelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue _lowerCamelCase : List[str] = html.unescape(__lowerCAmelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCAmelCase ) _lowerCamelCase, _lowerCamelCase : Optional[Any] = self.xpath_soup(__lowerCAmelCase ) stringaxtag_seq.append(__lowerCAmelCase ) stringaxsubs_seq.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) != len(__lowerCAmelCase ): raise ValueError("Number of doc strings and xtags does not correspond" ) if len(__lowerCAmelCase ) != len(__lowerCAmelCase ): raise ValueError("Number of doc strings and xsubs does not correspond" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _lowercase ( self: Tuple ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Tuple = "" for tagname, subs in zip(__lowerCAmelCase ,__lowerCAmelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self: List[str] ,__lowerCAmelCase: List[Any] ): '''simple docstring''' _lowerCamelCase : int = False # Check that strings has a valid type if isinstance(__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : Dict = True elif isinstance(__lowerCAmelCase ,(list, tuple) ): if len(__lowerCAmelCase ) == 0 or isinstance(html_strings[0] ,__lowerCAmelCase ): _lowerCamelCase : Tuple = True if not valid_strings: raise ValueError( "HTML strings must of type `str`, `List[str]` (batch of examples), " F"""but is of type {type(__lowerCAmelCase )}.""" ) _lowerCamelCase : Optional[int] = bool(isinstance(__lowerCAmelCase ,(list, tuple) ) and (isinstance(html_strings[0] ,__lowerCAmelCase )) ) if not is_batched: _lowerCamelCase : Dict = [html_strings] # Get nodes + xpaths _lowerCamelCase : List[Any] = [] _lowerCamelCase : List[Any] = [] for html_string in html_strings: _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : List[Any] = self.get_three_from_single(__lowerCAmelCase ) nodes.append(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = [] for node, tag_list, sub_list in zip(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ): _lowerCamelCase : Tuple = self.construct_xpath(__lowerCAmelCase ,__lowerCAmelCase ) xpath_strings.append(__lowerCAmelCase ) xpaths.append(__lowerCAmelCase ) # return as Dict _lowerCamelCase : Optional[Any] = {"nodes": nodes, "xpaths": xpaths} _lowerCamelCase : Union[str, Any] = BatchFeature(data=__lowerCAmelCase ,tensor_type=__lowerCAmelCase ) return encoded_inputs
46
import tensorflow as tf from ...tf_utils import shape_list class __lowerCAmelCase ( tf.keras.layers.Layer ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=1 , __magic_name__=False , **__magic_name__ ) -> Dict: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[Any] = vocab_size snake_case_ : Dict = d_embed snake_case_ : Union[str, Any] = d_proj snake_case_ : str = cutoffs + [vocab_size] snake_case_ : int = [0] + self.cutoffs snake_case_ : Optional[int] = div_val snake_case_ : int = self.cutoffs[0] snake_case_ : Any = len(self.cutoffs ) - 1 snake_case_ : Union[str, Any] = self.shortlist_size + self.n_clusters snake_case_ : str = keep_order snake_case_ : int = [] snake_case_ : Union[str, Any] = [] def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' if self.n_clusters > 0: snake_case_ : Tuple = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_weight''' ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_bias''' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: snake_case_ : List[str] = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' , ) self.out_projs.append(__magic_name__ ) else: self.out_projs.append(__magic_name__ ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : List[str] = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] snake_case_ : Optional[Any] = self.d_embed // (self.div_val**i) snake_case_ : int = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' ) self.out_projs.append(__magic_name__ ) snake_case_ : int = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : Any = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) super().build(__magic_name__ ) @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = x if proj is not None: snake_case_ : List[str] = tf.einsum('''ibd,ed->ibe''' , __magic_name__ , __magic_name__ ) return tf.einsum('''ibd,nd->ibn''' , __magic_name__ , __magic_name__ ) + b @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = shape_list(__magic_name__ ) snake_case_ : Tuple = tf.range(lp_size[0] , dtype=target.dtype ) snake_case_ : Dict = tf.stack([r, target] , 1 ) return tf.gather_nd(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=True , __magic_name__=False ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = 0 if self.n_clusters == 0: snake_case_ : Any = self._logit(__magic_name__ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: snake_case_ : Union[str, Any] = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__magic_name__ , logits=__magic_name__ ) snake_case_ : Optional[Any] = tf.nn.log_softmax(__magic_name__ , axis=-1 ) else: snake_case_ : Optional[int] = shape_list(__magic_name__ ) snake_case_ : int = [] snake_case_ : List[Any] = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: snake_case_ : str = (target >= l_idx) & (target < r_idx) snake_case_ : Dict = tf.where(__magic_name__ ) snake_case_ : List[str] = tf.boolean_mask(__magic_name__ , __magic_name__ ) - l_idx if self.div_val == 1: snake_case_ : Any = self.out_layers[0][0][l_idx:r_idx] snake_case_ : Dict = self.out_layers[0][1][l_idx:r_idx] else: snake_case_ : Union[str, Any] = self.out_layers[i][0] snake_case_ : int = self.out_layers[i][1] if i == 0: snake_case_ : List[Any] = tf.concat([cur_W, self.cluster_weight] , 0 ) snake_case_ : Tuple = tf.concat([cur_b, self.cluster_bias] , 0 ) snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[0] ) snake_case_ : Any = tf.nn.log_softmax(__magic_name__ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = self._gather_logprob(__magic_name__ , __magic_name__ ) else: snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[i] ) snake_case_ : Union[str, Any] = tf.nn.log_softmax(__magic_name__ ) snake_case_ : Optional[Any] = self.cutoffs[0] + i - 1 # No probability for the head cluster snake_case_ : Optional[int] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(__magic_name__ ) if target is not None: snake_case_ : Any = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : str = self._gather_logprob(__magic_name__ , __magic_name__ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(__magic_name__ , -cur_logprob , shape_list(__magic_name__ ) ) snake_case_ : str = tf.concat(__magic_name__ , axis=-1 ) if target is not None: if return_mean: snake_case_ : int = tf.reduce_mean(__magic_name__ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(__magic_name__ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(__magic_name__ , name=self.name , aggregation='''mean''' if return_mean else '''''' ) return out
60
0
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _UpperCamelCase( unittest.TestCase ): def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for a, b in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , delta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : List[Any] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' __a : int = None ops.enable_eager_execution_internal() __a : Optional[Any] = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __a : int = tf.config.list_logical_devices(device_type='CPU' ) __a : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __a : List[str] = GradientAccumulator() __a : Tuple = tf.Variable([4.0, 3.0] ) __a , __a : int = create_optimizer(5e-5 , 1_0 , 5 ) __a : List[Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE__ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE__ : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): with strategy.scope(): __a : Optional[Any] = strategy.experimental_local_results(SCREAMING_SNAKE_CASE__ ) local_variables[0].assign(SCREAMING_SNAKE_CASE__ ) local_variables[1].assign(SCREAMING_SNAKE_CASE__ ) strategy.run(SCREAMING_SNAKE_CASE__ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE__ ) def _check_local_values(SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ): __a : Union[str, Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE__ , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
47
import requests def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" snake_case_ : Tuple = {'''Content-Type''': '''application/json'''} snake_case_ : Any = requests.post(_UpperCamelCase , json={'''text''': message_body} , headers=_UpperCamelCase ) if response.status_code != 200: snake_case_ : List[Any] = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_UpperCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('''<YOUR MESSAGE BODY>''', '''<SLACK CHANNEL URL>''')
60
0
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 if start < end: lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ ,lowerCAmelCase__ = _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 A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ = 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__ = new_pivot_index + 1 lowerCAmelCase__ = a[new_pivot_index] lowerCAmelCase__ = a[index] lowerCAmelCase__ = temp lowerCAmelCase__ = a[new_pivot_index + 1] lowerCAmelCase__ = a[end] lowerCAmelCase__ = temp return new_pivot_index + 1, count UpperCAmelCase__ : Tuple = TemporaryFile() UpperCAmelCase__ : List[str] = 1_00 # 1000 elements are to be sorted UpperCAmelCase__ , UpperCAmelCase__ : Dict = 0, 1 # mean and standard deviation UpperCAmelCase__ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array UpperCAmelCase__ : Optional[Any] = np.load(outfile) UpperCAmelCase__ : Any = len(M) - 1 UpperCAmelCase__ : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
48
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
"""simple docstring""" def lowercase__ ( snake_case_ :dict ): __UpperCAmelCase = set() # To detect a back edge, keep track of vertices currently in the recursion stack __UpperCAmelCase = set() return any( node not in visited and depth_first_search(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) for node in graph ) def lowercase__ ( snake_case_ :dict , snake_case_ :int , snake_case_ :set , snake_case_ :set ): visited.add(snake_case_ ) rec_stk.add(snake_case_ ) for node in graph[vertex]: if node not in visited: if depth_first_search(snake_case_ , snake_case_ , snake_case_ , snake_case_ ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(snake_case_ ) return False if __name__ == "__main__": from doctest import testmod testmod()
49
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''', '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''', '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''owlvit_text_model''' def __init__(self , __magic_name__=4_9408 , __magic_name__=512 , __magic_name__=2048 , __magic_name__=12 , __magic_name__=8 , __magic_name__=16 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , __magic_name__=0 , __magic_name__=4_9406 , __magic_name__=4_9407 , **__magic_name__ , ) -> str: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : int = vocab_size snake_case_ : str = hidden_size snake_case_ : List[Any] = intermediate_size snake_case_ : str = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : str = hidden_act snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : Union[str, Any] = initializer_range snake_case_ : int = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : str = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit_vision_model''' def __init__(self , __magic_name__=768 , __magic_name__=3072 , __magic_name__=12 , __magic_name__=12 , __magic_name__=3 , __magic_name__=768 , __magic_name__=32 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : Union[str, Any] = intermediate_size snake_case_ : Union[str, Any] = num_hidden_layers snake_case_ : Tuple = num_attention_heads snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = image_size snake_case_ : Dict = patch_size snake_case_ : List[Any] = hidden_act snake_case_ : Tuple = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : List[str] = initializer_range snake_case_ : List[Any] = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : int = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit''' lowerCamelCase_ : Optional[int] = True def __init__(self , __magic_name__=None , __magic_name__=None , __magic_name__=512 , __magic_name__=2.6_592 , __magic_name__=True , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) if text_config is None: snake_case_ : Tuple = {} logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''' ) if vision_config is None: snake_case_ : str = {} logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''' ) snake_case_ : str = OwlViTTextConfig(**__magic_name__ ) snake_case_ : Union[str, Any] = OwlViTVisionConfig(**__magic_name__ ) snake_case_ : Any = projection_dim snake_case_ : Union[str, Any] = logit_scale_init_value snake_case_ : str = return_dict snake_case_ : Any = 1.0 @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = cls.get_config_dict(__magic_name__ , **__magic_name__ ) 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(__magic_name__ , **__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> str: '''simple docstring''' snake_case_ : Optional[int] = {} snake_case_ : Union[str, Any] = text_config snake_case_ : Optional[Any] = vision_config return cls.from_dict(__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = copy.deepcopy(self.__dict__ ) snake_case_ : List[Any] = self.text_config.to_dict() snake_case_ : List[Any] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ] ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''logits_per_image''', {0: '''batch'''}), ('''logits_per_text''', {0: '''batch'''}), ('''text_embeds''', {0: '''batch'''}), ('''image_embeds''', {0: '''batch'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-4 def lowerCamelCase (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Dict = super().generate_dummy_inputs( processor.tokenizer , batch_size=__magic_name__ , seq_length=__magic_name__ , framework=__magic_name__ ) snake_case_ : List[str] = super().generate_dummy_inputs( processor.image_processor , batch_size=__magic_name__ , framework=__magic_name__ ) return {**text_input_dict, **image_input_dict} @property def lowerCamelCase (self ) -> int: '''simple docstring''' return 14
60
0
'''simple docstring''' UpperCamelCase : Optional[int] = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} UpperCamelCase : Tuple = ['a', 'b', 'c', 'd', 'e'] def A__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict ): lowerCamelCase__ = start # add current to visited visited.append(__lowerCAmelCase ) lowerCamelCase__ = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: lowerCamelCase__ = topological_sort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # if all neighbors visited add current to sort sort.append(__lowerCAmelCase ) # if all vertices haven't been visited select a new one to visit if len(__lowerCAmelCase ) != len(__lowerCAmelCase ): for vertice in vertices: if vertice not in visited: lowerCamelCase__ = topological_sort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # return sort return sort if __name__ == "__main__": UpperCamelCase : int = topological_sort('a', [], []) print(sort)
50
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) lowerCamelCase_ : Union[str, Any] = ['''accelerate''', '''launch'''] lowerCamelCase_ : Tuple = Path.home() / '''.cache/huggingface/accelerate''' lowerCamelCase_ : Tuple = '''default_config.yaml''' lowerCamelCase_ : str = config_folder / config_file lowerCamelCase_ : List[Any] = config_folder / '''_default_config.yaml''' lowerCamelCase_ : Dict = Path('''tests/test_configs''' ) @classmethod def lowerCamelCase (cls ) -> Dict: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCamelCase (cls ) -> Any: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=__magic_name__ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(__magic_name__ ), self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''test-tpu''' lowerCamelCase_ : Dict = '''us-central1-a''' lowerCamelCase_ : Any = '''ls''' lowerCamelCase_ : Dict = ['''accelerate''', '''tpu-config'''] lowerCamelCase_ : Tuple = '''cd /usr/share''' lowerCamelCase_ : List[Any] = '''tests/test_samples/test_command_file.sh''' lowerCamelCase_ : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : int = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=__magic_name__ ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , )
60
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , a__ : Optional[Any] , a__ : Any=13 , a__ : str=3 , a__ : List[Any]=224 , a__ : Any=30 , a__ : List[Any]=400 , a__ : Optional[int]=True , a__ : str=None , a__ : Dict=True , a__ : Tuple=[0.5, 0.5, 0.5] , a__ : List[str]=[0.5, 0.5, 0.5] , ): UpperCAmelCase = size if size is not None else {'''height''': 18, '''width''': 18} UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_normalize UpperCAmelCase = image_mean UpperCAmelCase = image_std def __snake_case ( self : List[str] ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' _lowerCamelCase =ViTImageProcessor if is_vision_available() else None def __snake_case ( self : int ): UpperCAmelCase = EfficientFormerImageProcessorTester(self ) @property def __snake_case ( self : Optional[int] ): return self.image_proc_tester.prepare_image_processor_dict() def __snake_case ( self : Tuple ): UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a__ , '''image_mean''' ) ) self.assertTrue(hasattr(a__ , '''image_std''' ) ) self.assertTrue(hasattr(a__ , '''do_normalize''' ) ) self.assertTrue(hasattr(a__ , '''do_resize''' ) ) self.assertTrue(hasattr(a__ , '''size''' ) ) def __snake_case ( self : Optional[int] ): pass def __snake_case ( self : List[str] ): # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=a__ ) for image in image_inputs: self.assertIsInstance(a__ , Image.Image ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched UpperCAmelCase = image_processor(a__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __snake_case ( self : int ): # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=a__ , numpify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , np.ndarray ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched UpperCAmelCase = image_processor(a__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __snake_case ( self : List[Any] ): # Initialize image_processor UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_proc_tester , equal_resolution=a__ , torchify=a__ ) for image in image_inputs: self.assertIsInstance(a__ , torch.Tensor ) # Test not batched input UpperCAmelCase = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched UpperCAmelCase = image_processor(a__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
51
import warnings from ..trainer import Trainer from ..utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__=None , **__magic_name__ ) -> Dict: '''simple docstring''' warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , __magic_name__ , ) super().__init__(args=__magic_name__ , **__magic_name__ )
60
0
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def __A ( a_ :str) -> List[Any]: def decorator(a_ :List[Any]): __a : List[str] = getattr(a_ , '''handle_key''' , []) handle += [key] setattr(a_ , '''handle_key''' , a_) return func return decorator def __A ( *a_ :List[str]) -> Optional[int]: def decorator(a_ :int): __a : Tuple = getattr(a_ , '''handle_key''' , []) handle += keys setattr(a_ , '''handle_key''' , a_) return func return decorator class __lowercase ( _UpperCamelCase ): '''simple docstring''' def __new__( cls , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): __a : Tuple = super().__new__(cls , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if not hasattr(_UpperCAmelCase , '''key_handler''' ): setattr(_UpperCAmelCase , '''key_handler''' , {} ) setattr(_UpperCAmelCase , '''handle_input''' , KeyHandler.handle_input ) for value in attrs.values(): __a : Dict = getattr(_UpperCAmelCase , '''handle_key''' , [] ) for key in handled_keys: __a : Union[str, Any] = value return new_cls @staticmethod def _lowerCamelCase ( cls ): __a : Dict = get_character() if char != KEYMAP["undefined"]: __a : str = ord(_UpperCAmelCase ) __a : Tuple = cls.key_handler.get(_UpperCAmelCase ) if handler: __a : Union[str, Any] = char return handler(cls ) else: return None def __A ( cls :Union[str, Any]) -> str: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy())
52
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" snake_case_ : str = '''mock-s3-bucket''' snake_case_ : str = f'''s3://{mock_bucket}''' snake_case_ : Any = extract_path_from_uri(_UpperCamelCase ) assert dataset_path.startswith('''s3://''' ) is False snake_case_ : Optional[Any] = '''./local/path''' snake_case_ : List[str] = extract_path_from_uri(_UpperCamelCase ) assert dataset_path == new_dataset_path def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : Union[str, Any] = is_remote_filesystem(_UpperCamelCase ) assert is_remote is True snake_case_ : Union[str, Any] = fsspec.filesystem('''file''' ) snake_case_ : int = is_remote_filesystem(_UpperCamelCase ) assert is_remote is False @pytest.mark.parametrize('''compression_fs_class''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : Optional[Any] = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file} snake_case_ : Optional[Any] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case_ : List[Any] = f'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_UpperCamelCase ) snake_case_ : Dict = fsspec.filesystem(compression_fs_class.protocol , fo=_UpperCamelCase ) assert isinstance(_UpperCamelCase , _UpperCamelCase ) snake_case_ : int = os.path.basename(_UpperCamelCase ) snake_case_ : Any = expected_filename[: expected_filename.rindex('''.''' )] assert fs.glob('''*''' ) == [expected_filename] with fs.open(_UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f, open(_UpperCamelCase , encoding='''utf-8''' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('''protocol''' , ['''zip''', '''gzip'''] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Union[str, Any] = {'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path} snake_case_ : Any = compressed_file_paths[protocol] snake_case_ : Any = '''dataset.jsonl''' snake_case_ : Dict = f'''{protocol}://{member_file_path}::{compressed_file_path}''' snake_case_ , *snake_case_ : Optional[Any] = fsspec.get_fs_token_paths(_UpperCamelCase ) assert fs.isfile(_UpperCamelCase ) assert not fs.isfile('''non_existing_''' + member_file_path ) @pytest.mark.integration def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : Optional[int] = hf_api.dataset_info(_UpperCamelCase , token=_UpperCamelCase ) snake_case_ : List[str] = HfFileSystem(repo_info=_UpperCamelCase , token=_UpperCamelCase ) assert sorted(hffs.glob('''*''' ) ) == [".gitattributes", "data"] assert hffs.isdir('''data''' ) assert hffs.isfile('''.gitattributes''' ) and hffs.isfile('''data/text_data.txt''' ) with open(_UpperCamelCase ) as f: assert hffs.open('''data/text_data.txt''' , '''r''' ).read() == f.read() def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Tuple = '''bz2''' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_UpperCamelCase , _UpperCamelCase , clobber=_UpperCamelCase ) with pytest.warns(_UpperCamelCase ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_UpperCamelCase ) == 1 assert ( str(warning_info[0].message ) == f'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
60
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _snake_case : Any = logging.get_logger(__name__) _snake_case : int = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _snake_case : Optional[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _snake_case : str = { 'yjernite/retribert-base-uncased': 512, } _snake_case : Optional[int] = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class _UpperCAmelCase ( _UpperCamelCase ): """simple docstring""" a_ = VOCAB_FILES_NAMES a_ = PRETRAINED_VOCAB_FILES_MAP a_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a_ = PRETRAINED_INIT_CONFIGURATION a_ = RetriBertTokenizer a_ = ["""input_ids""", """attention_mask"""] def __init__( self : Dict , lowerCAmelCase_ : Optional[Any]=None , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : List[str]=True , lowerCAmelCase_ : str="[UNK]" , lowerCAmelCase_ : Optional[Any]="[SEP]" , lowerCAmelCase_ : List[str]="[PAD]" , lowerCAmelCase_ : Optional[int]="[CLS]" , lowerCAmelCase_ : List[Any]="[MASK]" , lowerCAmelCase_ : Optional[Any]=True , lowerCAmelCase_ : List[str]=None , **lowerCAmelCase_ : List[Any] , ) -> Dict: super().__init__( lowerCAmelCase_ , tokenizer_file=lowerCAmelCase_ , do_lower_case=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , tokenize_chinese_chars=lowerCAmelCase_ , strip_accents=lowerCAmelCase_ , **lowerCAmelCase_ , ) __lowerCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , lowerCAmelCase_ ) != do_lower_case or normalizer_state.get('strip_accents' , lowerCAmelCase_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , lowerCAmelCase_ ) != tokenize_chinese_chars ): __lowerCAmelCase = getattr(lowerCAmelCase_ , normalizer_state.pop('type' ) ) __lowerCAmelCase = do_lower_case __lowerCAmelCase = strip_accents __lowerCAmelCase = tokenize_chinese_chars __lowerCAmelCase = normalizer_class(**lowerCAmelCase_ ) __lowerCAmelCase = do_lower_case def lowercase ( self : str , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[int]=None ) -> Optional[int]: __lowerCAmelCase = [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 lowercase ( self : Union[str, Any] , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> List[int]: __lowerCAmelCase = [self.sep_token_id] __lowerCAmelCase = [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 lowercase ( self : int , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]: __lowerCAmelCase = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ )
53
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[Any] = '''encoder-decoder''' lowerCamelCase_ : Optional[Any] = True def __init__(self , **__magic_name__ ) -> Optional[int]: '''simple docstring''' super().__init__(**__magic_name__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" snake_case_ : Any = kwargs.pop('''encoder''' ) snake_case_ : Tuple = encoder_config.pop('''model_type''' ) snake_case_ : Union[str, Any] = kwargs.pop('''decoder''' ) snake_case_ : Union[str, Any] = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig snake_case_ : Optional[int] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : List[str] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : Any = True @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> PretrainedConfig: '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) snake_case_ : Tuple = True snake_case_ : Optional[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = copy.deepcopy(self.__dict__ ) snake_case_ : Any = self.encoder.to_dict() snake_case_ : Dict = self.decoder.to_dict() snake_case_ : Union[str, Any] = self.__class__.model_type return output
60
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo __lowercase : Optional[int] ="""\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ __lowercase : Dict ="""\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ __lowercase : List[str] ="""\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A ( datasets.Metric ): def lowerCAmelCase__ ( self: int ) -> MetricInfo: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def lowerCAmelCase__ ( self: List[str] , _lowerCAmelCase: List[List[List[str]]] , _lowerCAmelCase: List[List[str]] , _lowerCAmelCase: int = 1 , _lowerCAmelCase: int = 4 , ) -> Dict[str, float]: '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCAmelCase , hypotheses=_lowerCAmelCase , min_len=_lowerCAmelCase , max_len=_lowerCAmelCase ) }
54
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[int] = question_encoder snake_case_ : Optional[int] = generator snake_case_ : Optional[Any] = self.question_encoder def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' if os.path.isfile(__magic_name__ ): raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) snake_case_ : str = os.path.join(__magic_name__ , '''question_encoder_tokenizer''' ) snake_case_ : List[Any] = os.path.join(__magic_name__ , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(__magic_name__ ) self.generator.save_pretrained(__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> Any: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case_ : List[str] = kwargs.pop('''config''' , __magic_name__ ) if config is None: snake_case_ : int = RagConfig.from_pretrained(__magic_name__ ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=__magic_name__ , generator=__magic_name__ ) def __call__(self , *__magic_name__ , **__magic_name__ ) -> Tuple: '''simple docstring''' return self.current_tokenizer(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' return self.generator.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' return self.generator.decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.question_encoder def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.generator def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "longest" , __magic_name__ = None , __magic_name__ = True , **__magic_name__ , ) -> BatchEncoding: '''simple docstring''' warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , __magic_name__ , ) if max_length is None: snake_case_ : Dict = self.current_tokenizer.model_max_length snake_case_ : List[str] = self( __magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , max_length=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case_ : Optional[int] = self.current_tokenizer.model_max_length snake_case_ : Union[str, Any] = self( text_target=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , padding=__magic_name__ , max_length=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) snake_case_ : str = labels['''input_ids'''] return model_inputs
60
0
import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
import inspect import unittest from transformers import ViTMSNConfig 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 ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=30 , __magic_name__=2 , __magic_name__=3 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.02 , __magic_name__=None , ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : List[Any] = image_size snake_case_ : Optional[int] = patch_size snake_case_ : Optional[Any] = num_channels snake_case_ : Optional[Any] = is_training snake_case_ : List[Any] = use_labels snake_case_ : Optional[int] = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = intermediate_size snake_case_ : Any = hidden_act snake_case_ : List[str] = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : List[str] = type_sequence_label_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ : Any = (image_size // patch_size) ** 2 snake_case_ : int = num_patches + 1 def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : List[Any] = None if self.use_labels: snake_case_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : int = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = ViTMSNModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[str] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = self.type_sequence_label_size snake_case_ : Tuple = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Any = model(__magic_name__ , labels=__magic_name__ ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ : Optional[int] = 1 snake_case_ : List[str] = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ : Any = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ : Optional[int] = config_and_inputs snake_case_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () lowerCamelCase_ : Optional[int] = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[Any] = ViTMSNModelTester(self ) snake_case_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Any = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , nn.Linear ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Tuple = model_class(__magic_name__ ) snake_case_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : Optional[int] = [*signature.parameters.keys()] snake_case_ : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : str = ViTMSNModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' torch.manual_seed(2 ) snake_case_ : List[str] = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__magic_name__ ) snake_case_ : str = self.default_image_processor snake_case_ : str = prepare_img() snake_case_ : int = image_processor(images=__magic_name__ , return_tensors='''pt''' ).to(__magic_name__ ) # forward pass with torch.no_grad(): snake_case_ : Optional[int] = model(**__magic_name__ ) # verify the logits snake_case_ : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) snake_case_ : List[Any] = torch.tensor([-0.0_803, -0.4_454, -0.2_375] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1e-4 ) )
60
0
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def _a (lowercase__ : int ) -> bool: """simple docstring""" __snake_case = int(number**0.5 ) return number == sq * sq def _a (lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int ) -> tuple[int, int]: """simple docstring""" __snake_case = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __snake_case = x_den * y_den * z_den __snake_case = gcd(lowercase__ , lowercase__ ) top //= hcf bottom //= hcf return top, bottom def _a (lowercase__ : int = 3_5 ) -> int: """simple docstring""" __snake_case = set() __snake_case = 42 __snake_case = Fraction(0 ) __snake_case = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __snake_case = x_num * y_den + x_den * y_num __snake_case = x_den * y_den __snake_case = gcd(lowercase__ , lowercase__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __snake_case = add_three( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) unique_s.add(lowercase__ ) # n=2 __snake_case = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __snake_case = x_den * x_den * y_den * y_den if is_sq(lowercase__ ) and is_sq(lowercase__ ): __snake_case = int(sqrt(lowercase__ ) ) __snake_case = int(sqrt(lowercase__ ) ) __snake_case = gcd(lowercase__ , lowercase__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __snake_case = add_three( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) unique_s.add(lowercase__ ) # n=-1 __snake_case = x_num * y_num __snake_case = x_den * y_num + x_num * y_den __snake_case = gcd(lowercase__ , lowercase__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __snake_case = add_three( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) unique_s.add(lowercase__ ) # n=2 __snake_case = x_num * x_num * y_num * y_num __snake_case = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(lowercase__ ) and is_sq(lowercase__ ): __snake_case = int(sqrt(lowercase__ ) ) __snake_case = int(sqrt(lowercase__ ) ) __snake_case = gcd(lowercase__ , lowercase__ ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __snake_case = add_three( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) unique_s.add(lowercase__ ) for num, den in unique_s: total += Fraction(lowercase__ , lowercase__ ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
56
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = '''efficientnet''' def __init__(self , __magic_name__ = 3 , __magic_name__ = 600 , __magic_name__ = 2.0 , __magic_name__ = 3.1 , __magic_name__ = 8 , __magic_name__ = [3, 3, 5, 3, 5, 5, 3] , __magic_name__ = [32, 16, 24, 40, 80, 112, 192] , __magic_name__ = [16, 24, 40, 80, 112, 192, 320] , __magic_name__ = [] , __magic_name__ = [1, 2, 2, 2, 1, 2, 1] , __magic_name__ = [1, 2, 2, 3, 3, 4, 1] , __magic_name__ = [1, 6, 6, 6, 6, 6, 6] , __magic_name__ = 0.25 , __magic_name__ = "swish" , __magic_name__ = 2560 , __magic_name__ = "mean" , __magic_name__ = 0.02 , __magic_name__ = 0.001 , __magic_name__ = 0.99 , __magic_name__ = 0.5 , __magic_name__ = 0.2 , **__magic_name__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[str] = num_channels snake_case_ : Tuple = image_size snake_case_ : Union[str, Any] = width_coefficient snake_case_ : Tuple = depth_coefficient snake_case_ : Optional[Any] = depth_divisor snake_case_ : Optional[int] = kernel_sizes snake_case_ : str = in_channels snake_case_ : Optional[Any] = out_channels snake_case_ : int = depthwise_padding snake_case_ : Optional[Any] = strides snake_case_ : Any = num_block_repeats snake_case_ : Optional[Any] = expand_ratios snake_case_ : Union[str, Any] = squeeze_expansion_ratio snake_case_ : Union[str, Any] = hidden_act snake_case_ : Union[str, Any] = hidden_dim snake_case_ : Any = pooling_type snake_case_ : List[str] = initializer_range snake_case_ : str = batch_norm_eps snake_case_ : Optional[int] = batch_norm_momentum snake_case_ : Optional[Any] = dropout_rate snake_case_ : List[str] = drop_connect_rate snake_case_ : Union[str, Any] = sum(__magic_name__ ) * 4 class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = version.parse('''1.11''' ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-5
60
0
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : List[Any] =AutoencoderKL a : Union[str, Any] ='''sample''' a : Tuple =1e-2 @property def _a ( self ): UpperCamelCase_: Union[str, Any] = 4 UpperCamelCase_: Any = 3 UpperCamelCase_: str = (3_2, 3_2) UpperCamelCase_: Optional[Any] = floats_tensor((batch_size, num_channels) + sizes ).to(_lowerCamelCase ) return {"sample": image} @property def _a ( self ): return (3, 3_2, 3_2) @property def _a ( self ): return (3, 3_2, 3_2) def _a ( self ): UpperCamelCase_: List[Any] = { 'block_out_channels': [3_2, 6_4], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } UpperCamelCase_: Optional[Any] = self.dummy_input return init_dict, inputs_dict def _a ( self ): pass def _a ( self ): pass @unittest.skipIf(torch_device == 'mps' , 'Gradient checkpointing skipped on MPS' ) def _a ( self ): # enable deterministic behavior for gradient checkpointing UpperCamelCase_ ,UpperCamelCase_: Any = self.prepare_init_args_and_inputs_for_common() UpperCamelCase_: int = self.model_class(**_lowerCamelCase ) model.to(_lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training UpperCamelCase_: List[str] = model(**_lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() UpperCamelCase_: Dict = torch.randn_like(_lowerCamelCase ) UpperCamelCase_: str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCamelCase_: Any = self.model_class(**_lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(_lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCamelCase_: int = model_a(**_lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() UpperCamelCase_: Optional[int] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) UpperCamelCase_: Optional[Any] = dict(model.named_parameters() ) UpperCamelCase_: List[str] = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Tuple = AutoencoderKL.from_pretrained('fusing/autoencoder-kl-dummy' , output_loading_info=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(_lowerCamelCase ) UpperCamelCase_: Any = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _a ( self ): UpperCamelCase_: str = AutoencoderKL.from_pretrained('fusing/autoencoder-kl-dummy' ) UpperCamelCase_: Any = model.to(_lowerCamelCase ) model.eval() if torch_device == "mps": UpperCamelCase_: Optional[Any] = torch.manual_seed(0 ) else: UpperCamelCase_: List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) UpperCamelCase_: Optional[Any] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCamelCase_: Dict = image.to(_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: int = model(_lowerCamelCase , sample_posterior=_lowerCamelCase , generator=_lowerCamelCase ).sample UpperCamelCase_: Union[str, Any] = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": UpperCamelCase_: List[str] = torch.tensor( [ -4.0078e-01, -3.8323e-04, -1.2681e-01, -1.1462e-01, 2.0095e-01, 1.0893e-01, -8.8247e-02, -3.0361e-01, -9.8644e-03, ] ) elif torch_device == "cpu": UpperCamelCase_: List[str] = torch.tensor( [-0.1_3_5_2, 0.0_8_7_8, 0.0_4_1_9, -0.0_8_1_8, -0.1_0_6_9, 0.0_6_8_8, -0.1_4_5_8, -0.4_4_4_6, -0.0_0_2_6] ) else: UpperCamelCase_: int = torch.tensor( [-0.2_4_2_1, 0.4_6_4_2, 0.2_5_0_7, -0.0_4_3_8, 0.0_6_8_2, 0.3_1_6_0, -0.2_0_1_8, -0.0_7_2_7, 0.2_4_8_5] ) self.assertTrue(torch_all_close(_lowerCamelCase , _lowerCamelCase , rtol=1e-2 ) ) @slow class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self , _lowerCamelCase , _lowerCamelCase ): return f'''gaussian_noise_s={seed}_shape={'_'.join([str(_lowerCamelCase ) for s in shape] )}.npy''' def _a ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self , _lowerCamelCase=0 , _lowerCamelCase=(4, 3, 5_1_2, 5_1_2) , _lowerCamelCase=False ): UpperCamelCase_: Optional[Any] = torch.floataa if fpaa else torch.floataa UpperCamelCase_: Any = torch.from_numpy(load_hf_numpy(self.get_file_format(_lowerCamelCase , _lowerCamelCase ) ) ).to(_lowerCamelCase ).to(_lowerCamelCase ) return image def _a ( self , _lowerCamelCase="CompVis/stable-diffusion-v1-4" , _lowerCamelCase=False ): UpperCamelCase_: List[str] = 'fp16' if fpaa else None UpperCamelCase_: int = torch.floataa if fpaa else torch.floataa UpperCamelCase_: Optional[Any] = AutoencoderKL.from_pretrained( _lowerCamelCase , subfolder='vae' , torch_dtype=_lowerCamelCase , revision=_lowerCamelCase , ) model.to(_lowerCamelCase ).eval() return model def _a ( self , _lowerCamelCase=0 ): if torch_device == "mps": return torch.manual_seed(_lowerCamelCase ) return torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_6_0_3, 0.9_8_7_8, -0.0_4_9_5, -0.0_7_9_0, -0.2_7_0_9, 0.8_3_7_5, -0.2_0_6_0, -0.0_8_2_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [4_7, [-0.2_3_7_6, 0.1_1_6_8, 0.1_3_3_2, -0.4_8_4_0, -0.2_5_0_8, -0.0_7_9_1, -0.0_4_9_3, -0.4_0_8_9], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Any = self.get_sd_vae_model() UpperCamelCase_: str = self.get_sd_image(_lowerCamelCase ) UpperCamelCase_: int = self.get_generator(_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: List[str] = model(_lowerCamelCase , generator=_lowerCamelCase , sample_posterior=_lowerCamelCase ).sample assert sample.shape == image.shape UpperCamelCase_: Tuple = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCamelCase_: List[Any] = torch.tensor(expected_slice_mps if torch_device == 'mps' else expected_slice ) assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_5_1_3, 0.0_2_8_9, 1.3_7_9_9, 0.2_1_6_6, -0.2_5_7_3, -0.0_8_7_1, 0.5_1_0_3, -0.0_9_9_9]], [4_7, [-0.4_1_2_8, -0.1_3_2_0, -0.3_7_0_4, 0.1_9_6_5, -0.4_1_1_6, -0.2_3_3_2, -0.3_3_4_0, 0.2_2_4_7]], # fmt: on ] ) @require_torch_gpu def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[int] = self.get_sd_vae_model(fpaa=_lowerCamelCase ) UpperCamelCase_: str = self.get_sd_image(_lowerCamelCase , fpaa=_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = self.get_generator(_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , generator=_lowerCamelCase , sample_posterior=_lowerCamelCase ).sample assert sample.shape == image.shape UpperCamelCase_: str = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCamelCase_: Any = torch.tensor(_lowerCamelCase ) assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_6_0_9, 0.9_8_6_6, -0.0_4_8_7, -0.0_7_7_7, -0.2_7_1_6, 0.8_3_6_8, -0.2_0_5_5, -0.0_8_1_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [4_7, [-0.2_3_7_7, 0.1_1_4_7, 0.1_3_3_3, -0.4_8_4_1, -0.2_5_0_6, -0.0_8_0_5, -0.0_4_9_1, -0.4_0_8_5], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = self.get_sd_vae_model() UpperCamelCase_: Union[str, Any] = self.get_sd_image(_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: Optional[Any] = model(_lowerCamelCase ).sample assert sample.shape == image.shape UpperCamelCase_: List[str] = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCamelCase_: Any = torch.tensor(expected_slice_mps if torch_device == 'mps' else expected_slice ) assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_0_5_1, -0.1_8_0_3, -0.2_3_1_1, -0.2_1_1_4, -0.3_2_9_2, -0.3_5_7_4, -0.2_9_5_3, -0.3_3_2_3]], [3_7, [-0.2_6_3_2, -0.2_6_2_5, -0.2_1_9_9, -0.2_7_4_1, -0.4_5_3_9, -0.4_9_9_0, -0.3_7_2_0, -0.4_9_2_5]], # fmt: on ] ) @require_torch_gpu def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = self.get_sd_vae_model() UpperCamelCase_: Dict = self.get_sd_image(_lowerCamelCase , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): UpperCamelCase_: List[str] = model.decode(_lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] UpperCamelCase_: Any = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCamelCase_: Optional[Any] = torch.tensor(_lowerCamelCase ) assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_3_6_9, 0.0_2_0_7, -0.0_7_7_6, -0.0_6_8_2, -0.1_7_4_7, -0.1_9_3_0, -0.1_4_6_5, -0.2_0_3_9]], [1_6, [-0.1_6_2_8, -0.2_1_3_4, -0.2_7_4_7, -0.2_6_4_2, -0.3_7_7_4, -0.4_4_0_4, -0.3_6_8_7, -0.4_2_7_7]], # fmt: on ] ) @require_torch_gpu def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = self.get_sd_vae_model(fpaa=_lowerCamelCase ) UpperCamelCase_: int = self.get_sd_image(_lowerCamelCase , shape=(3, 4, 6_4, 6_4) , fpaa=_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: Tuple = model.decode(_lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] UpperCamelCase_: Any = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCamelCase_: Tuple = torch.tensor(_lowerCamelCase ) assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=5e-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='xformers is not required when using PyTorch 2.0.' ) def _a ( self , _lowerCamelCase ): UpperCamelCase_: List[str] = self.get_sd_vae_model(fpaa=_lowerCamelCase ) UpperCamelCase_: Optional[int] = self.get_sd_image(_lowerCamelCase , shape=(3, 4, 6_4, 6_4) , fpaa=_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: Optional[int] = model.decode(_lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCamelCase_: Tuple = model.decode(_lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=1e-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='xformers is not required when using PyTorch 2.0.' ) def _a ( self , _lowerCamelCase ): UpperCamelCase_: List[str] = self.get_sd_vae_model() UpperCamelCase_: Dict = self.get_sd_image(_lowerCamelCase , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): UpperCamelCase_: Optional[int] = model.decode(_lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCamelCase_: int = model.decode(_lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_0_0_1, 0.0_9_1_8, -2.6_9_8_4, -3.9_7_2_0, -3.2_0_9_9, -5.0_3_5_3, 1.7_3_3_8, -0.2_0_6_5, 3.4_2_6_7]], [4_7, [-1.5_0_3_0, -4.3_8_7_1, -6.0_3_5_5, -9.1_1_5_7, -1.6_6_6_1, -2.7_8_5_3, 2.1_6_0_7, -5.0_8_2_3, 2.5_6_3_3]], # fmt: on ] ) def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = self.get_sd_vae_model() UpperCamelCase_: int = self.get_sd_image(_lowerCamelCase ) UpperCamelCase_: Dict = self.get_generator(_lowerCamelCase ) with torch.no_grad(): UpperCamelCase_: str = model.encode(_lowerCamelCase ).latent_dist UpperCamelCase_: Union[str, Any] = dist.sample(generator=_lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCamelCase_: Any = sample[0, -1, -3:, -3:].flatten().cpu() UpperCamelCase_: Optional[int] = torch.tensor(_lowerCamelCase ) UpperCamelCase_: int = 3e-3 if torch_device != 'mps' else 1e-2 assert torch_all_close(_lowerCamelCase , _lowerCamelCase , atol=_lowerCamelCase )
57
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) lowerCAmelCase_ = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser( description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)''' ) parser.add_argument( '''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.''' ) parser.add_argument( '''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.''' ) parser.add_argument('''--vocab_size''', default=3_0_5_2_2, type=int) lowerCAmelCase_ = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, '''rb''') as fp: lowerCAmelCase_ = pickle.load(fp) logger.info('''Counting occurrences for MLM.''') lowerCAmelCase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase_ = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase_ = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, '''wb''') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
60
0
"""simple docstring""" from queue import PriorityQueue from typing import Any import numpy as np def __lowerCAmelCase ( __UpperCamelCase : dict , __UpperCamelCase : str , __UpperCamelCase : set , __UpperCamelCase : set , __UpperCamelCase : dict , __UpperCamelCase : dict , __UpperCamelCase : PriorityQueue , __UpperCamelCase : dict , __UpperCamelCase : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case_ : List[Any] = cst_fwd.get(__UpperCamelCase , np.inf ) snake_case_ : Optional[int] = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case_ : List[str] = new_cost_f snake_case_ : int = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case_ : Optional[int] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __lowerCAmelCase ( __UpperCamelCase : str , __UpperCamelCase : str , __UpperCamelCase : dict , __UpperCamelCase : dict ): '''simple docstring''' snake_case_ : List[Any] = -1 snake_case_ : List[Any] = set() snake_case_ : Union[str, Any] = set() snake_case_ : List[str] = {source: 0} snake_case_ : Optional[int] = {destination: 0} snake_case_ : List[Any] = {source: None} snake_case_ : str = {destination: None} snake_case_ : PriorityQueue[Any] = PriorityQueue() snake_case_ : PriorityQueue[Any] = PriorityQueue() snake_case_ : List[str] = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): snake_case_ , snake_case_ : Dict = queue_forward.get() visited_forward.add(__UpperCamelCase ) snake_case_ , snake_case_ : Dict = queue_backward.get() visited_backward.add(__UpperCamelCase ) snake_case_ : Optional[Any] = pass_and_relaxation( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ) snake_case_ : int = pass_and_relaxation( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case_ : List[str] = shortest_distance return shortest_path_distance __lowerCAmelCase : Union[str, Any] = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } __lowerCAmelCase : Tuple = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
58
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ = "▁" , __magic_name__ = True , __magic_name__ = "<unk>" , __magic_name__ = "</s>" , __magic_name__ = "<pad>" , ) -> Dict: '''simple docstring''' snake_case_ : List[Any] = { '''pad''': {'''id''': 0, '''token''': pad_token}, '''eos''': {'''id''': 1, '''token''': eos_token}, '''unk''': {'''id''': 2, '''token''': unk_token}, } snake_case_ : List[str] = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): snake_case_ : int = token_dict['''token'''] snake_case_ : Optional[int] = Tokenizer(Unigram() ) snake_case_ : int = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(''' {2,}''' ) , ''' ''' ), normalizers.Lowercase(), ] ) snake_case_ : Optional[int] = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ), pre_tokenizers.Digits(individual_digits=__magic_name__ ), pre_tokenizers.Punctuation(), ] ) snake_case_ : Tuple = decoders.Metaspace(replacement=__magic_name__ , add_prefix_space=__magic_name__ ) snake_case_ : Optional[Any] = TemplateProcessing( single=F'''$A {self.special_tokens["eos"]["token"]}''' , special_tokens=[(self.special_tokens['''eos''']['''token'''], self.special_tokens['''eos''']['''id'''])] , ) snake_case_ : Optional[Any] = { '''model''': '''SentencePieceUnigram''', '''replacement''': replacement, '''add_prefix_space''': add_prefix_space, } super().__init__(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) if isinstance(__magic_name__ , __magic_name__ ): snake_case_ : Dict = [files] self._tokenizer.train(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self , __magic_name__ , __magic_name__ = 8000 , __magic_name__ = True , ) -> int: '''simple docstring''' snake_case_ : Any = trainers.UnigramTrainer( vocab_size=__magic_name__ , special_tokens=self.special_tokens_list , show_progress=__magic_name__ , ) self._tokenizer.train_from_iterator(__magic_name__ , trainer=__magic_name__ ) self.add_unk_id() def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Tuple = json.loads(self._tokenizer.to_str() ) snake_case_ : Union[str, Any] = self.special_tokens['''unk''']['''id'''] snake_case_ : Tuple = Tokenizer.from_str(json.dumps(__magic_name__ ) )
60
0
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Dict: """simple docstring""" lowerCamelCase__: Optional[Any] =original_name.split("." )[0] lowerCamelCase__: Any =key.split("." ) lowerCamelCase__: Optional[Any] =int(key_list[key_list.index(__a ) - 2] ) lowerCamelCase__: List[str] =int(key_list[key_list.index(__a ) - 1] ) lowerCamelCase__: Union[str, Any] =orig_block_num - offset lowerCamelCase__: List[str] =key.replace(F"""{orig_block_num}.{layer_num}.{original_name}""" , F"""block.{new_block_num}.{layer_num}.{new_name}""" ) return key def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =OrderedDict() lowerCamelCase__ , lowerCamelCase__: int =0, 0 for key, value in state_dict.items(): if key.startswith("network" ): lowerCamelCase__: Union[str, Any] =key.replace("network" , "poolformer.encoder" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("bias" ) and "patch_embed" not in key: patch_emb_offset += 1 lowerCamelCase__: List[Any] =key[: key.find("proj" )] lowerCamelCase__: Optional[Any] =key.replace(__a , F"""patch_embeddings.{total_embed_found}.""" ) lowerCamelCase__: List[str] =key.replace("proj" , "projection" ) if key.endswith("bias" ): total_embed_found += 1 if "patch_embeddings" in key: lowerCamelCase__: Tuple ="poolformer.encoder." + key if "mlp.fc1" in key: lowerCamelCase__: Union[str, Any] =replace_key_with_offset(__a , __a , "mlp.fc1" , "output.conv1" ) if "mlp.fc2" in key: lowerCamelCase__: Optional[int] =replace_key_with_offset(__a , __a , "mlp.fc2" , "output.conv2" ) if "norm1" in key: lowerCamelCase__: Union[str, Any] =replace_key_with_offset(__a , __a , "norm1" , "before_norm" ) if "norm2" in key: lowerCamelCase__: List[str] =replace_key_with_offset(__a , __a , "norm2" , "after_norm" ) if "layer_scale_1" in key: lowerCamelCase__: str =replace_key_with_offset(__a , __a , "layer_scale_1" , "layer_scale_1" ) if "layer_scale_2" in key: lowerCamelCase__: Any =replace_key_with_offset(__a , __a , "layer_scale_2" , "layer_scale_2" ) if "head" in key: lowerCamelCase__: int =key.replace("head" , "classifier" ) lowerCamelCase__: List[str] =value return new_state_dict def lowerCAmelCase_ ( ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] ="http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase__: Optional[int] =Image.open(requests.get(__a , stream=__a ).raw ) return image @torch.no_grad() def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =PoolFormerConfig() # set attributes based on model_name lowerCamelCase__: int ="huggingface/label-files" lowerCamelCase__: Any =model_name[-3:] lowerCamelCase__: int =1000 lowerCamelCase__: List[Any] ="imagenet-1k-id2label.json" lowerCamelCase__: Any =(1, 1000) # set config attributes lowerCamelCase__: Optional[Any] =json.load(open(hf_hub_download(__a , __a , repo_type="dataset" ) , "r" ) ) lowerCamelCase__: Dict ={int(__a ): v for k, v in idalabel.items()} lowerCamelCase__: Optional[int] =idalabel lowerCamelCase__: int ={v: k for k, v in idalabel.items()} if size == "s12": lowerCamelCase__: Optional[int] =[2, 2, 6, 2] lowerCamelCase__: List[Any] =[64, 128, 320, 512] lowerCamelCase__: Optional[Any] =4.0 lowerCamelCase__: int =0.9 elif size == "s24": lowerCamelCase__: List[str] =[4, 4, 12, 4] lowerCamelCase__: str =[64, 128, 320, 512] lowerCamelCase__: Any =4.0 lowerCamelCase__: str =0.9 elif size == "s36": lowerCamelCase__: Any =[6, 6, 18, 6] lowerCamelCase__: Optional[int] =[64, 128, 320, 512] lowerCamelCase__: int =4.0 lowerCamelCase__: Dict =1e-6 lowerCamelCase__: Any =0.9 elif size == "m36": lowerCamelCase__: Union[str, Any] =[6, 6, 18, 6] lowerCamelCase__: Optional[Any] =[96, 192, 384, 768] lowerCamelCase__: Tuple =4.0 lowerCamelCase__: Union[str, Any] =1e-6 lowerCamelCase__: Optional[int] =0.9_5 elif size == "m48": lowerCamelCase__: Optional[Any] =[8, 8, 24, 8] lowerCamelCase__: str =[96, 192, 384, 768] lowerCamelCase__: Optional[int] =4.0 lowerCamelCase__: Dict =1e-6 lowerCamelCase__: Any =0.9_5 else: raise ValueError(F"""Size {size} not supported""" ) # load image processor lowerCamelCase__: str =PoolFormerImageProcessor(crop_pct=__a ) # Prepare image lowerCamelCase__: Optional[int] =prepare_img() lowerCamelCase__: Optional[int] =image_processor(images=__a , return_tensors="pt" ).pixel_values logger.info(F"""Converting model {model_name}...""" ) # load original state dict lowerCamelCase__: List[str] =torch.load(__a , map_location=torch.device("cpu" ) ) # rename keys lowerCamelCase__: List[Any] =rename_keys(__a ) # create HuggingFace model and load state dict lowerCamelCase__: List[str] =PoolFormerForImageClassification(__a ) model.load_state_dict(__a ) model.eval() # Define image processor lowerCamelCase__: Optional[int] =PoolFormerImageProcessor(crop_pct=__a ) lowerCamelCase__: Optional[int] =image_processor(images=prepare_img() , return_tensors="pt" ).pixel_values # forward pass lowerCamelCase__: List[Any] =model(__a ) lowerCamelCase__: Any =outputs.logits # define expected logit slices for different models if size == "s12": lowerCamelCase__: Optional[int] =torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": lowerCamelCase__: Union[str, Any] =torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": lowerCamelCase__: Dict =torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": lowerCamelCase__: Tuple =torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": lowerCamelCase__: Dict =torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(F"""Size {size} not supported""" ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , __a , atol=1e-2 ) # finally, save model and image processor logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(__a ).mkdir(exist_ok=__a ) model.save_pretrained(__a ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__a ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--model_name", default="poolformer_s12", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) __A = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
# 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 lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : List[Any] = [False] * len(_UpperCamelCase ) snake_case_ : int = [-1] * len(_UpperCamelCase ) def dfs(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Dict = True snake_case_ : Dict = 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 lowerCAmelCase_ = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
60
0
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) UpperCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _A ( lowerCAmelCase_ : str ): """simple docstring""" for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: lowerCAmelCase__ = model_type_to_module_name(lowerCAmelCase_ ) lowerCAmelCase__ = importlib.import_module(F'.{module_name}' , "transformers.models" ) try: return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase_ , "__name__" , lowerCAmelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowerCAmelCase__ = importlib.import_module("transformers" ) if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) return None def _A ( lowerCAmelCase_ : Union[str, os.PathLike] , lowerCAmelCase_ : Optional[Union[str, os.PathLike]] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : Optional[Dict[str, str]] = None , lowerCAmelCase_ : Optional[Union[bool, str]] = None , lowerCAmelCase_ : Optional[str] = None , lowerCAmelCase_ : bool = False , **lowerCAmelCase_ : Any , ): """simple docstring""" lowerCAmelCase__ = get_file_from_repo( lowerCAmelCase_ , lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , use_auth_token=lowerCAmelCase_ , revision=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead." ) return {} with open(lowerCAmelCase_ , encoding="utf-8" ) as reader: return json.load(lowerCAmelCase_ ) class __lowerCamelCase : """simple docstring""" def __init__( self : int ) -> int: raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(SCREAMING_SNAKE_CASE__ ) def a ( cls : str , SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: lowerCAmelCase__ = kwargs.pop("config" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = kwargs.pop("trust_remote_code" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = True lowerCAmelCase__ , lowerCAmelCase__ = FeatureExtractionMixin.get_feature_extractor_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = config_dict.get("feature_extractor_type" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): lowerCAmelCase__ = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # It could be in `config.feature_extractor_type`` lowerCAmelCase__ = getattr(SCREAMING_SNAKE_CASE__ , "feature_extractor_type" , SCREAMING_SNAKE_CASE__ ) if hasattr(SCREAMING_SNAKE_CASE__ , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: lowerCAmelCase__ = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: lowerCAmelCase__ = feature_extractor_class_from_name(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = feature_extractor_auto_map is not None lowerCAmelCase__ = feature_extractor_class is not None or type(SCREAMING_SNAKE_CASE__ ) in FEATURE_EXTRACTOR_MAPPING lowerCAmelCase__ = resolve_trust_remote_code( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if has_remote_code and trust_remote_code: lowerCAmelCase__ = get_class_from_dynamic_module( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = kwargs.pop("code_revision" , SCREAMING_SNAKE_CASE__ ) if os.path.isdir(SCREAMING_SNAKE_CASE__ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(SCREAMING_SNAKE_CASE__ ) in FEATURE_EXTRACTOR_MAPPING: lowerCAmelCase__ = FEATURE_EXTRACTOR_MAPPING[type(SCREAMING_SNAKE_CASE__ )] return feature_extractor_class.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) raise ValueError( f'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ' f'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ' f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' ) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: FEATURE_EXTRACTOR_MAPPING.register(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
61
import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=[0.5, 0.5, 0.5] , __magic_name__=False , ) -> int: '''simple docstring''' snake_case_ : int = size if size is not None else {'''height''': 20, '''width''': 20} snake_case_ : int = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} snake_case_ : str = parent snake_case_ : Optional[int] = batch_size snake_case_ : Dict = num_channels snake_case_ : List[Any] = image_size snake_case_ : Union[str, Any] = min_resolution snake_case_ : Tuple = max_resolution snake_case_ : str = do_resize snake_case_ : Tuple = size snake_case_ : int = do_center_crop snake_case_ : Tuple = crop_size snake_case_ : int = do_normalize snake_case_ : Optional[Any] = image_mean snake_case_ : List[str] = image_std snake_case_ : str = do_reduce_labels def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : Any = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Union[str, Any] = Image.open(dataset[0]['''file'''] ) snake_case_ : str = Image.open(dataset[1]['''file'''] ) return image, map def lowerCamelCase_ ( ) -> List[Any]: """simple docstring""" snake_case_ : str = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) snake_case_ : Optional[Any] = Image.open(ds[0]['''file'''] ) snake_case_ : Optional[Any] = Image.open(ds[1]['''file'''] ) snake_case_ : List[str] = Image.open(ds[2]['''file'''] ) snake_case_ : str = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = BeitImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : int = BeitImageProcessingTester(self ) @property def lowerCamelCase (self ) -> str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''center_crop''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_normalize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_mean''' ) ) self.assertTrue(hasattr(__magic_name__ , '''image_std''' ) ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) snake_case_ : Union[str, Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__magic_name__ ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) self.assertEqual(image_processor.do_reduce_labels , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' pass def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : Optional[int] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input snake_case_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case_ : List[str] = image_processing(__magic_name__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) snake_case_ : Union[str, Any] = [] for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input snake_case_ : List[str] = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched snake_case_ : Any = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test not batched input (PIL images) snake_case_ , snake_case_ : Optional[int] = prepare_semantic_single_inputs() snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched input (PIL images) snake_case_ , snake_case_ : Dict = prepare_semantic_batch_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 snake_case_ , snake_case_ : Tuple = prepare_semantic_single_inputs() snake_case_ : Optional[int] = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 150 ) snake_case_ : List[Any] = True snake_case_ : int = image_processing(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 )
60
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """huggingface/informer-tourism-monthly""": ( """https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json""" ), # See all Informer models at https://huggingface.co/models?filter=informer } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''informer''' UpperCamelCase_ : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Any , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "student_t" , UpperCAmelCase_ : str = "nll" , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : List[int] = None , 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 = 64 , 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_ : float = 0.05 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : int = 100 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str = "prob" , UpperCAmelCase_ : int = 5 , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Tuple , ): # time series specific configuration SCREAMING_SNAKE_CASE : str = prediction_length SCREAMING_SNAKE_CASE : List[str] = context_length or prediction_length SCREAMING_SNAKE_CASE : Optional[Any] = distribution_output SCREAMING_SNAKE_CASE : Tuple = loss SCREAMING_SNAKE_CASE : List[Any] = input_size SCREAMING_SNAKE_CASE : Any = num_time_features SCREAMING_SNAKE_CASE : List[str] = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] SCREAMING_SNAKE_CASE : List[Any] = scaling SCREAMING_SNAKE_CASE : List[Any] = num_dynamic_real_features SCREAMING_SNAKE_CASE : Dict = num_static_real_features SCREAMING_SNAKE_CASE : Dict = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(UpperCAmelCase_ ) != num_static_categorical_features: raise ValueError( "The cardinality should be a list of the same length as `num_static_categorical_features`" ) SCREAMING_SNAKE_CASE : Any = cardinality else: SCREAMING_SNAKE_CASE : Optional[int] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(UpperCAmelCase_ ) != num_static_categorical_features: raise ValueError( "The embedding dimension should be a list of the same length as `num_static_categorical_features`" ) SCREAMING_SNAKE_CASE : Tuple = embedding_dimension else: SCREAMING_SNAKE_CASE : List[str] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] SCREAMING_SNAKE_CASE : Optional[Any] = num_parallel_samples # Transformer architecture configuration SCREAMING_SNAKE_CASE : List[Any] = input_size * len(self.lags_sequence ) + self._number_of_features SCREAMING_SNAKE_CASE : Dict = d_model SCREAMING_SNAKE_CASE : List[str] = encoder_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = decoder_attention_heads SCREAMING_SNAKE_CASE : str = encoder_ffn_dim SCREAMING_SNAKE_CASE : Dict = decoder_ffn_dim SCREAMING_SNAKE_CASE : List[Any] = encoder_layers SCREAMING_SNAKE_CASE : Optional[Any] = decoder_layers SCREAMING_SNAKE_CASE : List[str] = dropout SCREAMING_SNAKE_CASE : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE : Dict = activation_dropout SCREAMING_SNAKE_CASE : List[str] = encoder_layerdrop SCREAMING_SNAKE_CASE : Tuple = decoder_layerdrop SCREAMING_SNAKE_CASE : str = activation_function SCREAMING_SNAKE_CASE : Union[str, Any] = init_std SCREAMING_SNAKE_CASE : Any = use_cache # Informer SCREAMING_SNAKE_CASE : Dict = attention_type SCREAMING_SNAKE_CASE : Dict = sampling_factor SCREAMING_SNAKE_CASE : Any = distil super().__init__(is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_ ) @property def _A ( self : Any ): 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 )
62
from sklearn.metrics import mean_squared_error import datasets lowerCAmelCase_ = '''\ @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} } ''' lowerCAmelCase_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' lowerCAmelCase_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__="uniform_average" , __magic_name__=True ) -> Any: '''simple docstring''' snake_case_ : List[Any] = mean_squared_error( __magic_name__ , __magic_name__ , sample_weight=__magic_name__ , multioutput=__magic_name__ , squared=__magic_name__ ) return {"mse": mse}
60
0
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path a : Dict = Path(__file__).resolve().parents[3] / "src" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) a : int = {"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"} a : List[Any] = "zero2" a : Union[str, Any] = "zero3" a : Optional[Any] = [ZEROa, ZEROa] def lowerCamelCase__ ( __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : int ): # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param __UpperCAmelCase : str = parameterized.to_safe_name("""_""".join(str(__lowerCamelCase ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test a : Tuple = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class a ( lowercase__ ): """simple docstring""" @parameterized.expand(__lowercase , name_func=__lowercase ) def UpperCAmelCase ( self : Optional[int] , __lowercase : Any , __lowercase : str ) -> Optional[int]: self.run_and_check( stage=__lowercase , model=__lowercase , distributed=__lowercase , fpaa=__lowercase , ) @require_torch_multi_gpu @parameterized.expand(__lowercase , name_func=__lowercase ) def UpperCAmelCase ( self : List[Any] , __lowercase : Any , __lowercase : Tuple ) -> Optional[int]: self.run_and_check( stage=__lowercase , model=__lowercase , distributed=__lowercase , fpaa=__lowercase , ) @parameterized.expand(__lowercase , name_func=__lowercase ) def UpperCAmelCase ( self : Union[str, Any] , __lowercase : str , __lowercase : Union[str, Any] ) -> Optional[Any]: self.run_and_check( stage=__lowercase , model=__lowercase , distributed=__lowercase , fpaa=__lowercase , ) @require_torch_multi_gpu @parameterized.expand(__lowercase , name_func=__lowercase ) def UpperCAmelCase ( self : Optional[Any] , __lowercase : List[Any] , __lowercase : Union[str, Any] ) -> Dict: self.run_and_check( stage=__lowercase , model=__lowercase , distributed=__lowercase , fpaa=__lowercase , ) def UpperCAmelCase ( self : List[str] , __lowercase : Optional[Any] ) -> Any: # XXX: run_asr is premature and doesn't save any results # so all we check for now is that the process didn't fail pass def UpperCAmelCase ( self : Any , __lowercase : str , __lowercase : str , __lowercase : int = 10 , __lowercase : bool = True , __lowercase : bool = True , __lowercase : bool = True , ) -> str: __UpperCAmelCase : Optional[Any] = models[model] __UpperCAmelCase : int = self.run_trainer( stage=__lowercase , model_name=__lowercase , eval_steps=__lowercase , num_train_epochs=1 , distributed=__lowercase , fpaa=__lowercase , ) self.do_checks(__lowercase ) return output_dir def UpperCAmelCase ( self : List[str] , __lowercase : str , __lowercase : str , __lowercase : int = 10 , __lowercase : int = 1 , __lowercase : bool = True , __lowercase : bool = True , ) -> Dict: __UpperCAmelCase : Optional[Any] = self.get_auto_remove_tmp_dir("""./xxx""" , after=__lowercase ) __UpperCAmelCase : List[str] = f""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(__lowercase )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files __UpperCAmelCase : Tuple = f"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() __UpperCAmelCase : Union[str, Any] = [f"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] __UpperCAmelCase : List[Any] = self.get_launcher(__lowercase ) __UpperCAmelCase : Tuple = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(__lowercase , env=self.get_env() ) return output_dir def UpperCAmelCase ( self : Tuple , __lowercase : List[Any]=False ) -> Tuple: # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup # - it won't be able to handle that # 2. for now testing with just 2 gpus max (since some quality tests may give different # results with mode gpus because we use very little data) __UpperCAmelCase : Optional[int] = min(2 , get_gpu_count() ) if distributed else 1 return f"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
63
import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class __lowerCAmelCase : lowerCamelCase_ : Any = None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) snake_case_ : List[Any] = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Optional[int] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : str = self.feature_extraction_class.from_json_file(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : str = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : Dict = self.feature_extraction_class.from_pretrained(__magic_name__ ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class() self.assertIsNotNone(__magic_name__ )
60
0
from __future__ import annotations from dataclasses import dataclass @dataclass class _lowerCamelCase : __a = 42 __a = None __a = None def A__ ( snake_case_ : TreeNode | None ): # Validation def is_valid_tree(snake_case_ : TreeNode | None ) -> bool: if node is None: return True if not isinstance(snake_case_ , snake_case_ ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(snake_case_ ): raise ValueError( '''Each node should be type of TreeNode and data should be float.''' ) def is_binary_search_tree_recursive_check( snake_case_ : TreeNode | None , snake_case_ : float , snake_case_ : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , snake_case_ , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , snake_case_ ) ) return is_binary_search_tree_recursive_check(snake_case_ , -float('''inf''' ) , float('''inf''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
64
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : str = None @staticmethod def lowerCamelCase () -> Any: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' raise NotImplementedError def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def lowerCamelCase (cls ) -> List[Any]: '''simple docstring''' return F'''`pip install {cls.pip_package or cls.name}`''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[int] = '''optuna''' @staticmethod def lowerCamelCase () -> Union[str, Any]: '''simple docstring''' return is_optuna_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Union[str, Any]: '''simple docstring''' return run_hp_search_optuna(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_optuna(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''ray''' lowerCamelCase_ : List[str] = '''\'ray[tune]\'''' @staticmethod def lowerCamelCase () -> List[Any]: '''simple docstring''' return is_ray_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_ray(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' return default_hp_space_ray(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''sigopt''' @staticmethod def lowerCamelCase () -> Optional[int]: '''simple docstring''' return is_sigopt_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> List[str]: '''simple docstring''' return run_hp_search_sigopt(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' return default_hp_space_sigopt(__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''wandb''' @staticmethod def lowerCamelCase () -> Dict: '''simple docstring''' return is_wandb_available() def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> Optional[Any]: '''simple docstring''' return run_hp_search_wandb(__magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return default_hp_space_wandb(__magic_name__ ) lowerCAmelCase_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_UpperCamelCase ) > 0: snake_case_ : Dict = available_backends[0].name if len(_UpperCamelCase ) > 1: logger.info( f'''{len(_UpperCamelCase )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( f''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
60
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowercase : def __init__( self : List[str] ,A : List[Any] ,A : List[str]=13 ,A : Any=32 ,A : List[str]=3 ,A : Optional[int]=4 ,A : Optional[int]=[10, 20, 30, 40] ,A : str=[2, 2, 3, 2] ,A : Optional[Any]=True ,A : Dict=True ,A : Tuple=37 ,A : List[str]="gelu" ,A : Optional[int]=10 ,A : List[Any]=0.0_2 ,A : Optional[int]=["stage2", "stage3", "stage4"] ,A : List[Any]=[2, 3, 4] ,A : List[Any]=None ,): '''simple docstring''' UpperCAmelCase__ : List[Any] = parent UpperCAmelCase__ : str = batch_size UpperCAmelCase__ : Union[str, Any] = image_size UpperCAmelCase__ : Any = num_channels UpperCAmelCase__ : Optional[int] = num_stages UpperCAmelCase__ : str = hidden_sizes UpperCAmelCase__ : List[Any] = depths UpperCAmelCase__ : str = is_training UpperCAmelCase__ : Dict = use_labels UpperCAmelCase__ : List[str] = intermediate_size UpperCAmelCase__ : List[Any] = hidden_act UpperCAmelCase__ : Optional[Any] = num_labels UpperCAmelCase__ : Union[str, Any] = initializer_range UpperCAmelCase__ : List[Any] = out_features UpperCAmelCase__ : Optional[Any] = out_indices UpperCAmelCase__ : Any = scope def __lowercase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : Tuple = None if self.use_labels: UpperCAmelCase__ : List[str] = ids_tensor([self.batch_size] ,self.num_labels ) UpperCAmelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowercase ( self : int ): '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=A ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def __lowercase ( self : str ,A : List[Any] ,A : Union[str, Any] ,A : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = ConvNextVaModel(config=A ) model.to(A ) model.eval() UpperCAmelCase__ : Union[str, Any] = model(A ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def __lowercase ( self : Union[str, Any] ,A : Union[str, Any] ,A : Optional[Any] ,A : List[str] ): '''simple docstring''' UpperCAmelCase__ : Dict = ConvNextVaForImageClassification(A ) model.to(A ) model.eval() UpperCAmelCase__ : Optional[int] = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : int ,A : Optional[int] ,A : Optional[int] ,A : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : int = ConvNextVaBackbone(config=A ) model.to(A ) model.eval() UpperCAmelCase__ : Tuple = model(A ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None UpperCAmelCase__ : List[Any] = None UpperCAmelCase__ : str = ConvNextVaBackbone(config=A ) model.to(A ) model.eval() UpperCAmelCase__ : str = model(A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : str ): '''simple docstring''' UpperCAmelCase__ : Dict = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = config_and_inputs UpperCAmelCase__ : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict def __lowercase ( self : str ): '''simple docstring''' UpperCAmelCase__ : Any = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = config_and_inputs UpperCAmelCase__ : Dict = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __lowercase ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): snake_case_ = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) snake_case_ = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def __lowercase ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ : Tuple = ConvNextVaModelTester(self ) UpperCAmelCase__ : Any = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def __lowercase ( self : List[str] ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : List[str] ): '''simple docstring''' return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def __lowercase ( self : str ): '''simple docstring''' pass def __lowercase ( self : List[Any] ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_with_labels() UpperCAmelCase__ : int = True if model_class.__name__ in [ *get_values(A ), *get_values(A ), ]: continue UpperCAmelCase__ : Tuple = model_class(A ) model.to(A ) model.train() UpperCAmelCase__ : List[Any] = self._prepare_for_class(A ,A ,return_labels=A ) UpperCAmelCase__ : Optional[int] = model(**A ).loss loss.backward() def __lowercase ( self : Tuple ): '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCAmelCase__ , UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_with_labels() UpperCAmelCase__ : int = False UpperCAmelCase__ : List[Any] = True if ( model_class.__name__ in [*get_values(A ), *get_values(A )] or not model_class.supports_gradient_checkpointing ): continue UpperCAmelCase__ : Dict = model_class(A ) model.to(A ) model.gradient_checkpointing_enable() model.train() UpperCAmelCase__ : Tuple = self._prepare_for_class(A ,A ,return_labels=A ) UpperCAmelCase__ : Optional[Any] = model(**A ).loss loss.backward() def __lowercase ( self : List[str] ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : List[Any] = model_class(A ) UpperCAmelCase__ : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : Optional[Any] = [*signature.parameters.keys()] UpperCAmelCase__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] ,A ) def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def __lowercase ( self : Any ): '''simple docstring''' def check_hidden_states_output(A : Optional[Any] ,A : Union[str, Any] ,A : str ): UpperCAmelCase__ : List[str] = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): UpperCAmelCase__ : int = model(**self._prepare_for_class(A ,A ) ) UpperCAmelCase__ : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCAmelCase__ : List[str] = self.model_tester.num_stages self.assertEqual(len(A ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) UpperCAmelCase__ , UpperCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Dict = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ : Tuple = True check_hidden_states_output(A ,A ,A ) def __lowercase ( self : int ): '''simple docstring''' UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def __lowercase ( self : Optional[Any] ): '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ : Tuple = ConvNextVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __lowercase ( unittest.TestCase ): @cached_property def __lowercase ( self : int ): '''simple docstring''' return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def __lowercase ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : int = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(A ) UpperCAmelCase__ : Any = self.default_image_processor UpperCAmelCase__ : str = prepare_img() UpperCAmelCase__ : List[Any] = preprocessor(images=A ,return_tensors="""pt""" ).to(A ) # forward pass with torch.no_grad(): UpperCAmelCase__ : Optional[int] = model(**A ) # verify the logits UpperCAmelCase__ : List[Any] = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape ,A ) UpperCAmelCase__ : Optional[Any] = torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1e-4 ) )
65
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> list: """simple docstring""" snake_case_ : Tuple = len(_UpperCamelCase ) snake_case_ : Union[str, Any] = [[0] * n for i in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): snake_case_ : Any = y_points[i] for i in range(2 , _UpperCamelCase ): for j in range(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[int] = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
60
0
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> List[Any]: _lowercase : int = model.config _lowercase : Tuple = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) _lowercase : Any = MBartConfig( is_decoder=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , add_cross_attention=SCREAMING_SNAKE_CASE , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=SCREAMING_SNAKE_CASE , add_final_layer_norm=SCREAMING_SNAKE_CASE , ) return encoder_config, decoder_config def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> int: if "encoder.model" in name: _lowercase : Any = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: _lowercase : str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: _lowercase : List[str] = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: _lowercase : Optional[Any] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: _lowercase : int = 'encoder.' + name if "attn.proj" in name: _lowercase : List[str] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: _lowercase : Optional[int] = name.replace('attn' , 'attention.self' ) if "norm1" in name: _lowercase : str = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _lowercase : Optional[int] = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _lowercase : int = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _lowercase : List[Any] = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": _lowercase : Optional[int] = 'encoder.layernorm.weight' if name == "encoder.norm.bias": _lowercase : str = 'encoder.layernorm.bias' return name def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: for key in orig_state_dict.copy().keys(): _lowercase : str = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if "qkv" in key: _lowercase : Tuple = key.split('.' ) _lowercase : Tuple = int(key_split[3] ) _lowercase : Any = int(key_split[5] ) _lowercase : str = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _lowercase : Optional[Any] = val[:dim, :] _lowercase : List[str] = val[dim : dim * 2, :] _lowercase : Tuple = val[-dim:, :] else: _lowercase : List[Any] = val[:dim] _lowercase : List[Any] = val[dim : dim * 2] _lowercase : int = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: _lowercase : List[str] = val return orig_state_dict def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=False ) -> Dict: # load original model _lowercase : str = DonutModel.from_pretrained(SCREAMING_SNAKE_CASE ).eval() # load HuggingFace model _lowercase , _lowercase : Any = get_configs(SCREAMING_SNAKE_CASE ) _lowercase : Any = DonutSwinModel(SCREAMING_SNAKE_CASE ) _lowercase : Optional[Any] = MBartForCausalLM(SCREAMING_SNAKE_CASE ) _lowercase : Tuple = VisionEncoderDecoderModel(encoder=SCREAMING_SNAKE_CASE , decoder=SCREAMING_SNAKE_CASE ) model.eval() _lowercase : List[str] = original_model.state_dict() _lowercase : str = convert_state_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) # verify results on scanned document _lowercase : List[str] = load_dataset('hf-internal-testing/example-documents' ) _lowercase : Optional[int] = dataset['test'][0]['image'].convert('RGB' ) _lowercase : Optional[Any] = XLMRobertaTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE , from_slow=SCREAMING_SNAKE_CASE ) _lowercase : Tuple = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) _lowercase : str = DonutProcessor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _lowercase : Optional[Any] = processor(SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": _lowercase : Tuple = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' _lowercase : int = 'When is the coffee break?' _lowercase : Optional[int] = task_prompt.replace('{user_input}' , SCREAMING_SNAKE_CASE ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": _lowercase : Any = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: _lowercase : List[Any] = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": _lowercase : Optional[Any] = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": _lowercase : List[str] = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt _lowercase : Tuple = 'hello world' else: raise ValueError('Model name not supported' ) _lowercase : Dict = original_model.decoder.tokenizer(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , return_tensors='pt' )[ 'input_ids' ] _lowercase : Any = original_model.encoder.model.patch_embed(SCREAMING_SNAKE_CASE ) _lowercase , _lowercase : int = model.encoder.embeddings(SCREAMING_SNAKE_CASE ) assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) # verify encoder hidden states _lowercase : str = original_model.encoder(SCREAMING_SNAKE_CASE ) _lowercase : List[str] = model.encoder(SCREAMING_SNAKE_CASE ).last_hidden_state assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-2 ) # verify decoder hidden states _lowercase : List[Any] = original_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).logits _lowercase : str = model(SCREAMING_SNAKE_CASE , decoder_input_ids=SCREAMING_SNAKE_CASE ).logits assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) UpperCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
66
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""") # TF training parameters snake_case = False snake_case = False def SCREAMING_SNAKE_CASE__ ( snake_case__ :Namespace ) -> Tuple: return TrainCommand(snake_case__ ) class A_ ( UpperCAmelCase ): """simple docstring""" @staticmethod def __UpperCAmelCase ( __A : ArgumentParser ) -> List[Any]: _lowercase = parser.add_parser('train' ,help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' ,type=__A ,required=__A ,help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' ,) train_parser.add_argument( '--column_label' ,type=__A ,default=0 ,help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' ,type=__A ,default=1 ,help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' ,type=__A ,default=2 ,help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' ,action='store_true' ,help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' ,type=__A ,default='' ,help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' ,type=__A ,default=0.1 ,help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' ,) train_parser.add_argument('--output' ,type=__A ,default='./' ,help='path to saved the trained model.' ) train_parser.add_argument( '--task' ,type=__A ,default='text_classification' ,help='Task to train the model on.' ) train_parser.add_argument( '--model' ,type=__A ,default='bert-base-uncased' ,help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' ,type=__A ,default=32 ,help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' ,type=__A ,default=64 ,help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' ,type=__A ,default=3e-5 ,help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' ,type=__A ,default=1e-08 ,help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=__A ) def __init__( self : Optional[Any] ,__A : Namespace ) -> Tuple: _lowercase = logging.get_logger('transformers-cli/training' ) _lowercase = 'tf' if is_tf_available() else 'torch' os.makedirs(args.output ,exist_ok=__A ) _lowercase = args.output _lowercase = args.column_label _lowercase = args.column_text _lowercase = args.column_id self.logger.info(F"""Loading {args.task} pipeline for {args.model}""" ) if args.task == "text_classification": _lowercase = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F"""Loading dataset from {args.train_data}""" ) _lowercase = Processor.create_from_csv( args.train_data ,column_label=args.column_label ,column_text=args.column_text ,column_id=args.column_id ,skip_first_row=args.skip_first_row ,) _lowercase = None if args.validation_data: self.logger.info(F"""Loading validation dataset from {args.validation_data}""" ) _lowercase = Processor.create_from_csv( args.validation_data ,column_label=args.column_label ,column_text=args.column_text ,column_id=args.column_id ,skip_first_row=args.skip_first_row ,) _lowercase = args.validation_split _lowercase = args.train_batch_size _lowercase = args.valid_batch_size _lowercase = args.learning_rate _lowercase = args.adam_epsilon def __UpperCAmelCase ( self : Optional[Any] ) -> str: if self.framework == "tf": return self.run_tf() return self.run_torch() def __UpperCAmelCase ( self : Tuple ) -> List[Any]: raise NotImplementedError def __UpperCAmelCase ( self : Optional[int] ) -> Optional[int]: self.pipeline.fit( self.train_dataset ,validation_data=self.valid_dataset ,validation_split=self.validation_split ,learning_rate=self.learning_rate ,adam_epsilon=self.adam_epsilon ,train_batch_size=self.train_batch_size ,valid_batch_size=self.valid_batch_size ,) # Save trained pipeline self.pipeline.save_pretrained(self.output )
67
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" return getitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" return setitem, k, v def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" return delitem, k def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) -> str: """simple docstring""" try: return fun(_UpperCamelCase , *_UpperCamelCase ), None except Exception as e: return None, e lowerCAmelCase_ = ( _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), ) lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_a''', '''val_b'''), ] lowerCAmelCase_ = [ _set('''key_a''', '''val_a'''), _set('''key_b''', '''val_b'''), _del('''key_a'''), _del('''key_b'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), ] lowerCAmelCase_ = [ _get('''key_a'''), _del('''key_a'''), _set('''key_a''', '''val_a'''), _del('''key_a'''), _del('''key_a'''), _get('''key_a'''), ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] lowerCAmelCase_ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('''key_a''', '''val_b'''), ] @pytest.mark.parametrize( '''operations''' , ( pytest.param(_add_items , id='''add items''' ), pytest.param(_overwrite_items , id='''overwrite items''' ), pytest.param(_delete_items , id='''delete items''' ), pytest.param(_access_absent_items , id='''access absent items''' ), pytest.param(_add_with_resize_up , id='''add with resize up''' ), pytest.param(_add_with_resize_down , id='''add with resize down''' ), ) , ) def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" snake_case_ : Any = HashMap(initial_block_size=4 ) snake_case_ : Union[str, Any] = {} for _, (fun, *args) in enumerate(_UpperCamelCase ): snake_case_ , snake_case_ : str = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = _run_operation(_UpperCamelCase , _UpperCamelCase , *_UpperCamelCase ) assert my_res == py_res assert str(_UpperCamelCase ) == str(_UpperCamelCase ) assert set(_UpperCamelCase ) == set(_UpperCamelCase ) assert len(_UpperCamelCase ) == len(_UpperCamelCase ) assert set(my.items() ) == set(py.items() ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" def is_public(_UpperCamelCase ) -> bool: return not name.startswith('''_''' ) snake_case_ : str = {name for name in dir({} ) if is_public(_UpperCamelCase )} snake_case_ : str = {name for name in dir(HashMap() ) if is_public(_UpperCamelCase )} assert dict_public_names > hash_public_names
60
0
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class _A ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase : Optional[int] = VQModel lowerCamelCase : Dict = 'sample' @property def _a ( self : List[Any] , __SCREAMING_SNAKE_CASE : Tuple=(32, 32) ) -> str: __UpperCAmelCase =4 __UpperCAmelCase =3 __UpperCAmelCase =floats_tensor((batch_size, num_channels) + sizes ).to(__SCREAMING_SNAKE_CASE ) return {"sample": image} @property def _a ( self : Any ) -> List[str]: return (3, 32, 32) @property def _a ( self : Optional[int] ) -> Tuple: return (3, 32, 32) def _a ( self : int ) -> int: __UpperCAmelCase ={ """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } __UpperCAmelCase =self.dummy_input return init_dict, inputs_dict def _a ( self : str ) -> Dict: pass def _a ( self : str ) -> Any: pass def _a ( self : Any ) -> str: __UpperCAmelCase , __UpperCAmelCase =VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _a ( self : Tuple ) -> str: __UpperCAmelCase =VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(__SCREAMING_SNAKE_CASE ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) __UpperCAmelCase =torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) __UpperCAmelCase =image.to(__SCREAMING_SNAKE_CASE ) with torch.no_grad(): __UpperCAmelCase =model(__SCREAMING_SNAKE_CASE ).sample __UpperCAmelCase =output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __UpperCAmelCase =torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-3 ) )
68
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase ) -> list: """simple docstring""" if len(_UpperCamelCase ) == 0: return [] snake_case_ , snake_case_ : Dict = min(_UpperCamelCase ), max(_UpperCamelCase ) snake_case_ : List[str] = int(max_value - min_value ) + 1 snake_case_ : list[list] = [[] for _ in range(_UpperCamelCase )] for i in my_list: buckets[int(i - min_value )].append(_UpperCamelCase ) return [v for bucket in buckets for v in sorted(_UpperCamelCase )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -1_0, 1_5, 2, -2]) == [-1_0, -2, 0, 1, 2, 1_5]
60
0
'''simple docstring''' from __future__ import annotations from collections.abc import MutableSequence class SCREAMING_SNAKE_CASE__ : def __init__( self : Optional[Any] , a_ : int , a_ : MutableSequence[float] ): """simple docstring""" if len(a_ ) != degree + 1: raise ValueError( "The number of coefficients should be equal to the degree + 1." ) __snake_case = list(a_ ) __snake_case = degree def __add__( self : List[str] , a_ : Polynomial ): """simple docstring""" if self.degree > polynomial_a.degree: __snake_case = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , a_ ) else: __snake_case = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , a_ ) def __sub__( self : Any , a_ : Polynomial ): """simple docstring""" return self + polynomial_a * Polynomial(0 , [-1] ) def __neg__( self : Union[str, Any] ): """simple docstring""" return Polynomial(self.degree , [-c for c in self.coefficients] ) def __mul__( self : Optional[int] , a_ : Polynomial ): """simple docstring""" __snake_case = [0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1 ): for j in range(polynomial_a.degree + 1 ): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree , a_ ) def A ( self : str , a_ : int | float ): """simple docstring""" __snake_case = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : str ): """simple docstring""" __snake_case = "" for i in range(self.degree , -1 , -1 ): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i] ) ) elif i == 1: polynomial += str(abs(self.coefficients[i] ) ) + "x" else: polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(a_ ) return polynomial def __repr__( self : str ): """simple docstring""" return self.__str__() def A ( self : Tuple ): """simple docstring""" __snake_case = [0] * self.degree for i in range(self.degree ): __snake_case = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , a_ ) def A ( self : List[Any] , a_ : int | float = 0 ): """simple docstring""" __snake_case = [0] * (self.degree + 2) __snake_case = constant for i in range(self.degree + 1 ): __snake_case = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , a_ ) def __eq__( self : Union[str, Any] , a_ : object ): """simple docstring""" if not isinstance(a_ , a_ ): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1 ): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self : int , a_ : object ): """simple docstring""" return not self.__eq__(a_ )
69
import tensorflow as tf from ...tf_utils import shape_list class __lowerCAmelCase ( tf.keras.layers.Layer ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=1 , __magic_name__=False , **__magic_name__ ) -> Dict: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[Any] = vocab_size snake_case_ : Dict = d_embed snake_case_ : Union[str, Any] = d_proj snake_case_ : str = cutoffs + [vocab_size] snake_case_ : int = [0] + self.cutoffs snake_case_ : Optional[int] = div_val snake_case_ : int = self.cutoffs[0] snake_case_ : Any = len(self.cutoffs ) - 1 snake_case_ : Union[str, Any] = self.shortlist_size + self.n_clusters snake_case_ : str = keep_order snake_case_ : int = [] snake_case_ : Union[str, Any] = [] def lowerCamelCase (self , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' if self.n_clusters > 0: snake_case_ : Tuple = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_weight''' ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=__magic_name__ , name='''cluster_bias''' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: snake_case_ : List[str] = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' , ) self.out_projs.append(__magic_name__ ) else: self.out_projs.append(__magic_name__ ) snake_case_ : Optional[Any] = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : List[str] = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] snake_case_ : Optional[Any] = self.d_embed // (self.div_val**i) snake_case_ : int = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_projs_._{i}''' ) self.out_projs.append(__magic_name__ ) snake_case_ : int = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._weight''' , ) snake_case_ : Any = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=__magic_name__ , name=F'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias) ) super().build(__magic_name__ ) @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None ) -> str: '''simple docstring''' snake_case_ : Union[str, Any] = x if proj is not None: snake_case_ : List[str] = tf.einsum('''ibd,ed->ibe''' , __magic_name__ , __magic_name__ ) return tf.einsum('''ibd,nd->ibn''' , __magic_name__ , __magic_name__ ) + b @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' snake_case_ : Union[str, Any] = shape_list(__magic_name__ ) snake_case_ : Tuple = tf.range(lp_size[0] , dtype=target.dtype ) snake_case_ : Dict = tf.stack([r, target] , 1 ) return tf.gather_nd(__magic_name__ , __magic_name__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__=True , __magic_name__=False ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = 0 if self.n_clusters == 0: snake_case_ : Any = self._logit(__magic_name__ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: snake_case_ : Union[str, Any] = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__magic_name__ , logits=__magic_name__ ) snake_case_ : Optional[Any] = tf.nn.log_softmax(__magic_name__ , axis=-1 ) else: snake_case_ : Optional[int] = shape_list(__magic_name__ ) snake_case_ : int = [] snake_case_ : List[Any] = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): snake_case_ , snake_case_ : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: snake_case_ : str = (target >= l_idx) & (target < r_idx) snake_case_ : Dict = tf.where(__magic_name__ ) snake_case_ : List[str] = tf.boolean_mask(__magic_name__ , __magic_name__ ) - l_idx if self.div_val == 1: snake_case_ : Any = self.out_layers[0][0][l_idx:r_idx] snake_case_ : Dict = self.out_layers[0][1][l_idx:r_idx] else: snake_case_ : Union[str, Any] = self.out_layers[i][0] snake_case_ : int = self.out_layers[i][1] if i == 0: snake_case_ : List[Any] = tf.concat([cur_W, self.cluster_weight] , 0 ) snake_case_ : Tuple = tf.concat([cur_b, self.cluster_bias] , 0 ) snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[0] ) snake_case_ : Any = tf.nn.log_softmax(__magic_name__ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Tuple = self._gather_logprob(__magic_name__ , __magic_name__ ) else: snake_case_ : Optional[int] = self._logit(__magic_name__ , __magic_name__ , __magic_name__ , self.out_projs[i] ) snake_case_ : Union[str, Any] = tf.nn.log_softmax(__magic_name__ ) snake_case_ : Optional[Any] = self.cutoffs[0] + i - 1 # No probability for the head cluster snake_case_ : Optional[int] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(__magic_name__ ) if target is not None: snake_case_ : Any = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : Optional[Any] = tf.boolean_mask(__magic_name__ , __magic_name__ ) snake_case_ : str = self._gather_logprob(__magic_name__ , __magic_name__ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(__magic_name__ , -cur_logprob , shape_list(__magic_name__ ) ) snake_case_ : str = tf.concat(__magic_name__ , axis=-1 ) if target is not None: if return_mean: snake_case_ : int = tf.reduce_mean(__magic_name__ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(__magic_name__ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(__magic_name__ , name=self.name , aggregation='''mean''' if return_mean else '''''' ) return out
60
0
def _SCREAMING_SNAKE_CASE ( lowercase : int = 50 ): '''simple docstring''' lowerCamelCase_ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
70
import requests def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" snake_case_ : Tuple = {'''Content-Type''': '''application/json'''} snake_case_ : Any = requests.post(_UpperCamelCase , json={'''text''': message_body} , headers=_UpperCamelCase ) if response.status_code != 200: snake_case_ : List[Any] = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_UpperCamelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('''<YOUR MESSAGE BODY>''', '''<SLACK CHANNEL URL>''')
60
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class _snake_case (__SCREAMING_SNAKE_CASE): __A : torch.FloatTensor __A : torch.FloatTensor __A : Optional[torch.FloatTensor] =None class _snake_case (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): __A : List[Any] =2 @register_to_config def __init__( self ,_snake_case = 0.02 ,_snake_case = 1_00 ,_snake_case = 1.007 ,_snake_case = 80 ,_snake_case = 0.05 ,_snake_case = 50 ,): # standard deviation of the initial noise distribution UpperCAmelCase_ : List[str] = sigma_max # setable values UpperCAmelCase_ : int = None UpperCAmelCase_ : np.IntTensor = None UpperCAmelCase_ : torch.FloatTensor = None # sigma(t_i) def UpperCamelCase__ ( self ,_snake_case ,_snake_case = None ): return sample def UpperCamelCase__ ( self ,_snake_case ,_snake_case = None ): UpperCAmelCase_ : Optional[Any] = num_inference_steps UpperCAmelCase_ : Any = np.arange(0 ,self.num_inference_steps )[::-1].copy() UpperCAmelCase_ : int = torch.from_numpy(_snake_case ).to(_snake_case ) UpperCAmelCase_ : str = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] UpperCAmelCase_ : List[Any] = torch.tensor(_snake_case ,dtype=torch.floataa ,device=_snake_case ) def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case = None ): if self.config.s_min <= sigma <= self.config.s_max: UpperCAmelCase_ : List[Any] = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: UpperCAmelCase_ : Any = 0 # sample eps ~ N(0, S_noise^2 * I) UpperCAmelCase_ : int = self.config.s_noise * randn_tensor(sample.shape ,generator=_snake_case ).to(sample.device ) UpperCAmelCase_ : str = sigma + gamma * sigma UpperCAmelCase_ : Dict = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case = True ,): UpperCAmelCase_ : Optional[int] = sample_hat + sigma_hat * model_output UpperCAmelCase_ : Dict = (sample_hat - pred_original_sample) / sigma_hat UpperCAmelCase_ : Union[str, Any] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_snake_case ,derivative=_snake_case ,pred_original_sample=_snake_case ) def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case = True ,): UpperCAmelCase_ : List[Any] = sample_prev + sigma_prev * model_output UpperCAmelCase_ : Union[str, Any] = (sample_prev - pred_original_sample) / sigma_prev UpperCAmelCase_ : Optional[int] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=_snake_case ,derivative=_snake_case ,pred_original_sample=_snake_case ) def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ): raise NotImplementedError()
71
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
0
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser _UpperCAmelCase : Optional[int] = re.compile(r'''\s+''') def UpperCamelCase ( lowercase_ : Dict ) -> Any: '''simple docstring''' return {"hash": hashlib.mda(re.sub(lowercase_ , '''''' , example['''content'''] ).encode('''utf-8''' ) ).hexdigest()} def UpperCamelCase ( lowercase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowercase =[len(lowercase_ ) for line in example['''content'''].splitlines()] return {"line_mean": np.mean(lowercase_ ), "line_max": max(lowercase_ )} def UpperCamelCase ( lowercase_ : Union[str, Any] ) -> str: '''simple docstring''' lowercase =np.mean([c.isalnum() for c in example['''content''']] ) return {"alpha_frac": alpha_frac} def UpperCamelCase ( lowercase_ : List[str] , lowercase_ : int ) -> Optional[Any]: '''simple docstring''' if example["hash"] in uniques: uniques.remove(example['''hash'''] ) return True else: return False def UpperCamelCase ( lowercase_ : Optional[int] , lowercase_ : Optional[Any]=5 ) -> int: '''simple docstring''' lowercase =['''auto-generated''', '''autogenerated''', '''automatically generated'''] lowercase =example['''content'''].splitlines() for _, line in zip(range(lowercase_ ) , lowercase_ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCamelCase ( lowercase_ : Any , lowercase_ : Optional[Any]=5 , lowercase_ : List[Any]=0.0_5 ) -> Optional[Any]: '''simple docstring''' lowercase =['''unit tests''', '''test file''', '''configuration file'''] lowercase =example['''content'''].splitlines() lowercase =0 lowercase =0 # first test for _, line in zip(range(lowercase_ ) , lowercase_ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test lowercase =example['''content'''].count('''\n''' ) lowercase =int(coeff * nlines ) for line in lines: count_config += line.lower().count('''config''' ) count_test += line.lower().count('''test''' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCamelCase ( lowercase_ : str ) -> List[str]: '''simple docstring''' lowercase =['''def ''', '''class ''', '''for ''', '''while '''] lowercase =example['''content'''].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCamelCase ( lowercase_ : Union[str, Any] , lowercase_ : str=4 ) -> int: '''simple docstring''' lowercase =example['''content'''].splitlines() lowercase =0 for line in lines: counter += line.lower().count('''=''' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCamelCase ( lowercase_ : Union[str, Any] ) -> int: '''simple docstring''' lowercase =tokenizer(example['''content'''] , truncation=lowercase_ )['''input_ids'''] lowercase =len(example['''content'''] ) / len(lowercase_ ) return {"ratio": ratio} def UpperCamelCase ( lowercase_ : List[Any] ) -> int: '''simple docstring''' lowercase ={} results.update(get_hash(lowercase_ ) ) results.update(line_stats(lowercase_ ) ) results.update(alpha_stats(lowercase_ ) ) results.update(char_token_ratio(lowercase_ ) ) results.update(is_autogenerated(lowercase_ ) ) results.update(is_config_or_test(lowercase_ ) ) results.update(has_no_keywords(lowercase_ ) ) results.update(has_few_assignments(lowercase_ ) ) return results def UpperCamelCase ( lowercase_ : Any , lowercase_ : Any , lowercase_ : Dict ) -> Optional[int]: '''simple docstring''' if not check_uniques(lowercase_ , lowercase_ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCamelCase ( lowercase_ : str ) -> List[str]: '''simple docstring''' with open(lowercase_ , '''rb''' ) as f_in: with gzip.open(str(lowercase_ ) + '''.gz''' , '''wb''' , compresslevel=6 ) as f_out: shutil.copyfileobj(lowercase_ , lowercase_ ) os.unlink(lowercase_ ) # Settings _UpperCAmelCase : Any = HfArgumentParser(PreprocessingArguments) _UpperCAmelCase : Tuple = parser.parse_args() if args.num_workers is None: _UpperCAmelCase : str = multiprocessing.cpu_count() _UpperCAmelCase : Any = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset _UpperCAmelCase : int = time.time() _UpperCAmelCase : Optional[Any] = load_dataset(args.dataset_name, split='''train''') print(F"""Time to load dataset: {time.time()-t_start:.2f}""") # Run preprocessing _UpperCAmelCase : int = time.time() _UpperCAmelCase : Optional[Any] = ds.map(preprocess, num_proc=args.num_workers) print(F"""Time to preprocess dataset: {time.time()-t_start:.2f}""") # Deduplicate hashes _UpperCAmelCase : Tuple = set(ds.unique('''hash''')) _UpperCAmelCase : Optional[int] = len(uniques) / len(ds) print(F"""Fraction of duplicates: {1-frac:.2%}""") # Deduplicate data and apply heuristics _UpperCAmelCase : Dict = time.time() _UpperCAmelCase : Tuple = ds.filter(filter, fn_kwargs={'''uniques''': uniques, '''args''': args}) print(F"""Time to filter dataset: {time.time()-t_start:.2f}""") print(F"""Size of filtered dataset: {len(ds_filter)}""") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: _UpperCAmelCase : str = time.time() _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"""Time to deduplicate dataset: {time.time()-t_start:.2f}""") print(F"""Size of deduplicate dataset: {len(ds_filter)}""") # Save data in batches of samples_per_file _UpperCAmelCase : Tuple = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / '''duplicate_clusters.json''', '''w''') as f: json.dump(duplicate_clusters, f) _UpperCAmelCase : List[str] = output_dir / '''data''' data_dir.mkdir(exist_ok=True) _UpperCAmelCase : List[str] = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): _UpperCAmelCase : Dict = str(data_dir / F"""file-{file_number+1:012}.json""") _UpperCAmelCase : List[str] = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"""Time to save dataset: {time.time()-t_start:.2f}""")
72
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''', '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''', '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''owlvit_text_model''' def __init__(self , __magic_name__=4_9408 , __magic_name__=512 , __magic_name__=2048 , __magic_name__=12 , __magic_name__=8 , __magic_name__=16 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , __magic_name__=0 , __magic_name__=4_9406 , __magic_name__=4_9407 , **__magic_name__ , ) -> str: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : int = vocab_size snake_case_ : str = hidden_size snake_case_ : List[Any] = intermediate_size snake_case_ : str = num_hidden_layers snake_case_ : List[Any] = num_attention_heads snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : str = hidden_act snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : Union[str, Any] = initializer_range snake_case_ : int = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : str = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit_vision_model''' def __init__(self , __magic_name__=768 , __magic_name__=3072 , __magic_name__=12 , __magic_name__=12 , __magic_name__=3 , __magic_name__=768 , __magic_name__=32 , __magic_name__="quick_gelu" , __magic_name__=1e-5 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=1.0 , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : Optional[Any] = hidden_size snake_case_ : Union[str, Any] = intermediate_size snake_case_ : Union[str, Any] = num_hidden_layers snake_case_ : Tuple = num_attention_heads snake_case_ : List[Any] = num_channels snake_case_ : Union[str, Any] = image_size snake_case_ : Dict = patch_size snake_case_ : List[Any] = hidden_act snake_case_ : Tuple = layer_norm_eps snake_case_ : Dict = attention_dropout snake_case_ : List[str] = initializer_range snake_case_ : List[Any] = initializer_factor @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : int = cls.get_config_dict(__magic_name__ , **__magic_name__ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('''model_type''' ) == "owlvit": snake_case_ : str = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__magic_name__ , **__magic_name__ ) class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''owlvit''' lowerCamelCase_ : Optional[int] = True def __init__(self , __magic_name__=None , __magic_name__=None , __magic_name__=512 , __magic_name__=2.6_592 , __magic_name__=True , **__magic_name__ , ) -> int: '''simple docstring''' super().__init__(**__magic_name__ ) if text_config is None: snake_case_ : Tuple = {} logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.''' ) if vision_config is None: snake_case_ : str = {} logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.''' ) snake_case_ : str = OwlViTTextConfig(**__magic_name__ ) snake_case_ : Union[str, Any] = OwlViTVisionConfig(**__magic_name__ ) snake_case_ : Any = projection_dim snake_case_ : Union[str, Any] = logit_scale_init_value snake_case_ : str = return_dict snake_case_ : Any = 1.0 @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__magic_name__ ) snake_case_ , snake_case_ : Optional[Any] = cls.get_config_dict(__magic_name__ , **__magic_name__ ) 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(__magic_name__ , **__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> str: '''simple docstring''' snake_case_ : Optional[int] = {} snake_case_ : Union[str, Any] = text_config snake_case_ : Optional[Any] = vision_config return cls.from_dict(__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Dict = copy.deepcopy(self.__dict__ ) snake_case_ : List[Any] = self.text_config.to_dict() snake_case_ : List[Any] = self.vision_config.to_dict() snake_case_ : Tuple = self.__class__.model_type return output class __lowerCAmelCase ( _a ): @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ] ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''logits_per_image''', {0: '''batch'''}), ('''logits_per_text''', {0: '''batch'''}), ('''text_embeds''', {0: '''batch'''}), ('''image_embeds''', {0: '''batch'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-4 def lowerCamelCase (self , __magic_name__ , __magic_name__ = -1 , __magic_name__ = -1 , __magic_name__ = None , ) -> Mapping[str, Any]: '''simple docstring''' snake_case_ : Dict = super().generate_dummy_inputs( processor.tokenizer , batch_size=__magic_name__ , seq_length=__magic_name__ , framework=__magic_name__ ) snake_case_ : List[str] = super().generate_dummy_inputs( processor.image_processor , batch_size=__magic_name__ , framework=__magic_name__ ) return {**text_input_dict, **image_input_dict} @property def lowerCamelCase (self ) -> int: '''simple docstring''' return 14
60
0
import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device a_ : List[Any] = False class _snake_case ( unittest.TestCase ): pass @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion') pipe.to(a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg') SCREAMING_SNAKE_CASE = torch.manual_seed(0) SCREAMING_SNAKE_CASE = pipe( image=a , generator=a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images SCREAMING_SNAKE_CASE = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE = np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
73
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Tuple = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) lowerCamelCase_ : Union[str, Any] = ['''accelerate''', '''launch'''] lowerCamelCase_ : Tuple = Path.home() / '''.cache/huggingface/accelerate''' lowerCamelCase_ : Tuple = '''default_config.yaml''' lowerCamelCase_ : str = config_folder / config_file lowerCamelCase_ : List[Any] = config_folder / '''_default_config.yaml''' lowerCamelCase_ : Dict = Path('''tests/test_configs''' ) @classmethod def lowerCamelCase (cls ) -> Dict: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCamelCase (cls ) -> Any: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Dict = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ): with self.subTest(config_file=__magic_name__ ): execute_subprocess_async( self.base_cmd + ['''--config_file''', str(__magic_name__ ), self.test_file_path] , env=os.environ.copy() ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() ) class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : List[str] = '''test-tpu''' lowerCamelCase_ : Dict = '''us-central1-a''' lowerCamelCase_ : Any = '''ls''' lowerCamelCase_ : Dict = ['''accelerate''', '''tpu-config'''] lowerCamelCase_ : Tuple = '''cd /usr/share''' lowerCamelCase_ : List[Any] = '''tests/test_samples/test_command_file.sh''' lowerCamelCase_ : List[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : int = run_command( self.cmd + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=__magic_name__ ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--command''', '''echo "Hello World"''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Tuple = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/0_12_0.yaml''', '''--command_file''', self.command_file, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = run_command( self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Optional[Any] = run_command( self.cmd + [ '''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--accelerate_version''', '''12.0.0''', '''--debug''', ] , return_stdout=__magic_name__ , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , __magic_name__ , )
60
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowercase_ = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowercase_ = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowercase_ = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } lowercase_ = { """facebook/dpr-ctx_encoder-single-nq-base""": 512, """facebook/dpr-ctx_encoder-multiset-base""": 512, } lowercase_ = { """facebook/dpr-question_encoder-single-nq-base""": 512, """facebook/dpr-question_encoder-multiset-base""": 512, } lowercase_ = { """facebook/dpr-reader-single-nq-base""": 512, """facebook/dpr-reader-multiset-base""": 512, } lowercase_ = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } lowercase_ = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } lowercase_ = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ = DPRContextEncoderTokenizer class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ = DPRQuestionEncoderTokenizer lowercase_ = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) lowercase_ = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) lowercase_ = R""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(lowerCAmelCase__ ) class __UpperCamelCase : """simple docstring""" def __call__( self : List[str] , _A : Tuple , _A : Optional[str] = None , _A : Optional[str] = None , _A : Union[bool, str] = False , _A : Union[bool, str] = False , _A : Optional[int] = None , _A : Optional[Union[str, TensorType]] = None , _A : Optional[bool] = None , **_A : Dict , ): """simple docstring""" if titles is None and texts is None: return super().__call__( _A , padding=_A , truncation=_A , max_length=_A , return_tensors=_A , return_attention_mask=_A , **_A , ) elif titles is None or texts is None: __SCREAMING_SNAKE_CASE : Tuple = titles if texts is None else texts return super().__call__( _A , _A , padding=_A , truncation=_A , max_length=_A , return_tensors=_A , return_attention_mask=_A , **_A , ) __SCREAMING_SNAKE_CASE : List[Any] = titles if not isinstance(_A , _A ) else [titles] __SCREAMING_SNAKE_CASE : Any = texts if not isinstance(_A , _A ) else [texts] __SCREAMING_SNAKE_CASE : List[Any] = len(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = questions if not isinstance(_A , _A ) else [questions] * n_passages assert len(_A ) == len( _A ), F'''There should be as many titles than texts but got {len(_A )} titles and {len(_A )} texts.''' __SCREAMING_SNAKE_CASE : Tuple = super().__call__(_A , _A , padding=_A , truncation=_A )['''input_ids'''] __SCREAMING_SNAKE_CASE : Any = super().__call__(_A , add_special_tokens=_A , padding=_A , truncation=_A )['''input_ids'''] __SCREAMING_SNAKE_CASE : str = { '''input_ids''': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_A , _A ) ] } if return_attention_mask is not False: __SCREAMING_SNAKE_CASE : Union[str, Any] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __SCREAMING_SNAKE_CASE : str = attention_mask return self.pad(_A , padding=_A , max_length=_A , return_tensors=_A ) def UpperCAmelCase__ ( self : int , _A : BatchEncoding , _A : DPRReaderOutput , _A : int = 16 , _A : int = 64 , _A : int = 4 , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = reader_input['''input_ids'''] __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = reader_output[:3] __SCREAMING_SNAKE_CASE : int = len(_A ) __SCREAMING_SNAKE_CASE : str = sorted(range(_A ) , reverse=_A , key=relevance_logits.__getitem__ ) __SCREAMING_SNAKE_CASE : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __SCREAMING_SNAKE_CASE : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __SCREAMING_SNAKE_CASE : Optional[int] = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __SCREAMING_SNAKE_CASE : int = sequence_ids.index(self.pad_token_id ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = len(_A ) __SCREAMING_SNAKE_CASE : Tuple = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_A , top_spans=_A , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_A , start_index=_A , end_index=_A , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_A ) >= num_spans: break return nbest_spans_predictions[:num_spans] def UpperCAmelCase__ ( self : List[str] , _A : List[int] , _A : List[int] , _A : int , _A : int , ): """simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [] for start_index, start_score in enumerate(_A ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __SCREAMING_SNAKE_CASE : Optional[Any] = sorted(_A , key=lambda _A : x[1] , reverse=_A ) __SCREAMING_SNAKE_CASE : int = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' __SCREAMING_SNAKE_CASE : Dict = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_A ) == top_spans: break return chosen_span_intervals @add_end_docstrings(lowerCAmelCase__ ) class __UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = READER_PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = READER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = DPRReaderTokenizer
74
import warnings from ..trainer import Trainer from ..utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__=None , **__magic_name__ ) -> Dict: '''simple docstring''' warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , __magic_name__ , ) super().__init__(args=__magic_name__ , **__magic_name__ )
60
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class lowerCamelCase_ ( __a ): def __init__( self : List[str] , _A : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : List[Any] = data def __iter__( self : List[Any] ): '''simple docstring''' for element in self.data: yield element def a__ ( lowerCAmelCase__=True ) -> str: UpperCAmelCase__ : Optional[int] = Accelerator(even_batches=lowerCAmelCase__ ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> Optional[int]: if iterable: UpperCAmelCase__ : int = DummyIterableDataset(torch.as_tensor(range(lowerCAmelCase__ ) ) ) else: UpperCAmelCase__ : str = TensorDataset(torch.as_tensor(range(lowerCAmelCase__ ) ) ) UpperCAmelCase__ : int = DataLoader(lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) UpperCAmelCase__ : Optional[Any] = accelerator.prepare(lowerCAmelCase__ ) return dl def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Union[str, Any]: UpperCAmelCase__ : List[str] = create_dataloader(accelerator=lowerCAmelCase__ , dataset_size=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) UpperCAmelCase__ : str = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def a__ ( ) -> Tuple: UpperCAmelCase__ : Tuple = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( lowerCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( lowerCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def a__ ( ) -> List[Any]: UpperCAmelCase__ : Any = create_accelerator(even_batches=lowerCAmelCase__ ) verify_dataloader_batch_sizes( lowerCAmelCase__ , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( lowerCAmelCase__ , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def a__ ( ) -> Optional[Any]: UpperCAmelCase__ : List[str] = create_accelerator(even_batches=lowerCAmelCase__ ) UpperCAmelCase__ : str = torch.nn.Linear(1 , 1 ) UpperCAmelCase__ : Union[str, Any] = accelerator.prepare(lowerCAmelCase__ ) UpperCAmelCase__ : Tuple = create_dataloader(lowerCAmelCase__ , dataset_size=3 , batch_size=1 ) UpperCAmelCase__ : Optional[int] = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(lowerCAmelCase__ ): UpperCAmelCase__ : Any = ddp_model(batch[0].float() ) UpperCAmelCase__ : Dict = output.sum() loss.backward() batch_idxs.append(lowerCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def a__ ( lowerCAmelCase__ ) -> Tuple: with warnings.catch_warnings(record=lowerCAmelCase__ ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , lowerCAmelCase__ ) assert "only supported for multi-GPU" in str(w[-1].message ) def a__ ( ) -> Optional[int]: UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : int = False UpperCAmelCase__ : Tuple = create_accelerator(even_batches=lowerCAmelCase__ ) UpperCAmelCase__ : List[Any] = torch.nn.Linear(1 , 1 ) UpperCAmelCase__ : List[Any] = accelerator.prepare(lowerCAmelCase__ ) UpperCAmelCase__ : Tuple = create_dataloader(lowerCAmelCase__ , dataset_size=3 , batch_size=1 ) UpperCAmelCase__ : Optional[int] = create_dataloader(lowerCAmelCase__ , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=lowerCAmelCase__ ): UpperCAmelCase__ : Optional[int] = train_dl.batch_sampler.even_batches UpperCAmelCase__ : Optional[Any] = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def a__ ( ) -> str: UpperCAmelCase__ : List[str] = True UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : str = create_accelerator(even_batches=lowerCAmelCase__ ) UpperCAmelCase__ : List[str] = torch.nn.Linear(1 , 1 ) UpperCAmelCase__ : str = accelerator.prepare(lowerCAmelCase__ ) create_dataloader(lowerCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=lowerCAmelCase__ ) UpperCAmelCase__ : Tuple = create_dataloader(lowerCAmelCase__ , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('''ignore''' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=lowerCAmelCase__ ): UpperCAmelCase__ : Union[str, Any] = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def a__ ( ) -> int: UpperCAmelCase__ : Union[str, Any] = create_accelerator() UpperCAmelCase__ : List[str] = torch.nn.Linear(1 , 1 ) UpperCAmelCase__ : int = accelerator.prepare(lowerCAmelCase__ ) create_dataloader(lowerCAmelCase__ , dataset_size=3 , batch_size=1 , iterable=lowerCAmelCase__ ) with warnings.catch_warnings(record=lowerCAmelCase__ ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=lowerCAmelCase__ ): pass assert issubclass(w[-1].category , lowerCAmelCase__ ) assert "only supported for map-style datasets" in str(w[-1].message ) def a__ ( ) -> Optional[Any]: UpperCAmelCase__ : Union[str, Any] = create_accelerator() accelerator.print('''Test that even_batches variable ensures uniform batches across processes''' ) test_default_ensures_even_batch_sizes() accelerator.print('''Run tests with even_batches disabled''' ) test_can_disable_even_batches() accelerator.print('''Test joining uneven inputs''' ) test_can_join_uneven_inputs() accelerator.print('''Test overriding even_batches when joining uneven inputs''' ) test_join_can_override_even_batches() accelerator.print('''Test overriding even_batches for mixed dataloader types''' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('''Test overriding even_batches raises a warning for iterable dataloaders''' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('''Test join with non DDP distributed raises warning''' ) UpperCAmelCase__ : Tuple = accelerator.state.distributed_type UpperCAmelCase__ : Dict = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(lowerCAmelCase__ ) UpperCAmelCase__ : int = original_state if __name__ == "__main__": main()
75
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCamelCase_ ( _UpperCamelCase ) -> Any: """simple docstring""" assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCamelCase_ ( ) -> Tuple: """simple docstring""" snake_case_ : str = '''mock-s3-bucket''' snake_case_ : str = f'''s3://{mock_bucket}''' snake_case_ : Any = extract_path_from_uri(_UpperCamelCase ) assert dataset_path.startswith('''s3://''' ) is False snake_case_ : Optional[Any] = '''./local/path''' snake_case_ : List[str] = extract_path_from_uri(_UpperCamelCase ) assert dataset_path == new_dataset_path def lowerCamelCase_ ( _UpperCamelCase ) -> str: """simple docstring""" snake_case_ : Union[str, Any] = is_remote_filesystem(_UpperCamelCase ) assert is_remote is True snake_case_ : Union[str, Any] = fsspec.filesystem('''file''' ) snake_case_ : int = is_remote_filesystem(_UpperCamelCase ) assert is_remote is False @pytest.mark.parametrize('''compression_fs_class''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : Optional[Any] = {'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_file, '''bz2''': bza_file, '''lz4''': lza_file} snake_case_ : Optional[Any] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case_ : List[Any] = f'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_UpperCamelCase ) snake_case_ : Dict = fsspec.filesystem(compression_fs_class.protocol , fo=_UpperCamelCase ) assert isinstance(_UpperCamelCase , _UpperCamelCase ) snake_case_ : int = os.path.basename(_UpperCamelCase ) snake_case_ : Any = expected_filename[: expected_filename.rindex('''.''' )] assert fs.glob('''*''' ) == [expected_filename] with fs.open(_UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f, open(_UpperCamelCase , encoding='''utf-8''' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('''protocol''' , ['''zip''', '''gzip'''] ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Union[str, Any] = {'''zip''': zip_jsonl_path, '''gzip''': jsonl_gz_path} snake_case_ : Any = compressed_file_paths[protocol] snake_case_ : Any = '''dataset.jsonl''' snake_case_ : Dict = f'''{protocol}://{member_file_path}::{compressed_file_path}''' snake_case_ , *snake_case_ : Optional[Any] = fsspec.get_fs_token_paths(_UpperCamelCase ) assert fs.isfile(_UpperCamelCase ) assert not fs.isfile('''non_existing_''' + member_file_path ) @pytest.mark.integration def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : Optional[int] = hf_api.dataset_info(_UpperCamelCase , token=_UpperCamelCase ) snake_case_ : List[str] = HfFileSystem(repo_info=_UpperCamelCase , token=_UpperCamelCase ) assert sorted(hffs.glob('''*''' ) ) == [".gitattributes", "data"] assert hffs.isdir('''data''' ) assert hffs.isfile('''.gitattributes''' ) and hffs.isfile('''data/text_data.txt''' ) with open(_UpperCamelCase ) as f: assert hffs.open('''data/text_data.txt''' , '''r''' ).read() == f.read() def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Tuple = '''bz2''' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_UpperCamelCase , _UpperCamelCase , clobber=_UpperCamelCase ) with pytest.warns(_UpperCamelCase ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_UpperCamelCase ) == 1 assert ( str(warning_info[0].message ) == f'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
60
0
"""simple docstring""" import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if isinstance(__UpperCamelCase , __UpperCamelCase ): __lowercase : Optional[int] = np.full((len(__UpperCamelCase ), sequence_length, 2) , __UpperCamelCase ) else: __lowercase : Optional[Any] = np.full((len(__UpperCamelCase ), sequence_length) , __UpperCamelCase ) for i, tensor in enumerate(__UpperCamelCase ): if padding_side == "right": if isinstance(__UpperCamelCase , __UpperCamelCase ): __lowercase : int = tensor[:sequence_length] else: __lowercase : Optional[Any] = tensor[:sequence_length] else: if isinstance(__UpperCamelCase , __UpperCamelCase ): __lowercase : str = tensor[:sequence_length] else: __lowercase : Union[str, Any] = tensor[:sequence_length] return out_tensor.tolist() def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Dict = ord(__UpperCamelCase ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26): return True __lowercase : List[str] = unicodedata.category(__UpperCamelCase ) if cat.startswith('''P''' ): return True return False @dataclass class UpperCAmelCase_ ( snake_case ): UpperCamelCase =42 UpperCamelCase =True UpperCamelCase =None UpperCamelCase =None UpperCamelCase =-1_00 UpperCamelCase ="pt" def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[str]: import torch __lowercase : int = '''label''' if '''label''' in features[0].keys() else '''labels''' __lowercase : int = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __lowercase : List[Any] = self.tokenizer.pad( UpperCamelCase_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch __lowercase : Union[str, Any] = torch.tensor(batch['''entity_ids'''] ).shape[1] __lowercase : Optional[int] = self.tokenizer.padding_side if padding_side == "right": __lowercase : Tuple = [ list(UpperCamelCase_ ) + [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase_ )) for label in labels ] else: __lowercase : int = [ [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase_ )) + list(UpperCamelCase_ ) for label in labels ] __lowercase : int = [feature['''ner_tags'''] for feature in features] __lowercase : Any = padding_tensor(UpperCamelCase_ , -1 , UpperCamelCase_ , UpperCamelCase_ ) __lowercase : Dict = [feature['''original_entity_spans'''] for feature in features] __lowercase : Dict = padding_tensor(UpperCamelCase_ , (-1, -1) , UpperCamelCase_ , UpperCamelCase_ ) __lowercase : Dict = {k: torch.tensor(UpperCamelCase_ , dtype=torch.intaa ) for k, v in batch.items()} return batch
76
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): lowerCamelCase_ : Optional[Any] = '''encoder-decoder''' lowerCamelCase_ : Optional[Any] = True def __init__(self , **__magic_name__ ) -> Optional[int]: '''simple docstring''' super().__init__(**__magic_name__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" snake_case_ : Any = kwargs.pop('''encoder''' ) snake_case_ : Tuple = encoder_config.pop('''model_type''' ) snake_case_ : Union[str, Any] = kwargs.pop('''decoder''' ) snake_case_ : Union[str, Any] = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig snake_case_ : Optional[int] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : List[str] = AutoConfig.for_model(__magic_name__ , **__magic_name__ ) snake_case_ : Any = True @classmethod def lowerCamelCase (cls , __magic_name__ , __magic_name__ , **__magic_name__ ) -> PretrainedConfig: '''simple docstring''' logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' ) snake_case_ : Tuple = True snake_case_ : Optional[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : str = copy.deepcopy(self.__dict__ ) snake_case_ : Any = self.encoder.to_dict() snake_case_ : Dict = self.decoder.to_dict() snake_case_ : Union[str, Any] = self.__class__.model_type return output
60
0
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() A = logging.get_logger(__name__) def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> List[str]: """simple docstring""" __UpperCAmelCase : Any = WavaVecaForSequenceClassification.from_pretrained(UpperCamelCase , config=UpperCamelCase ) __UpperCAmelCase : int = downstream_dict["projector.weight"] __UpperCAmelCase : List[Any] = downstream_dict["projector.bias"] __UpperCAmelCase : Optional[Any] = downstream_dict["model.post_net.linear.weight"] __UpperCAmelCase : List[Any] = downstream_dict["model.post_net.linear.bias"] return model def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase : Union[str, Any] = WavaVecaForAudioFrameClassification.from_pretrained(UpperCamelCase , config=UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = downstream_dict["model.linear.weight"] __UpperCAmelCase : Union[str, Any] = downstream_dict["model.linear.bias"] return model def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> int: """simple docstring""" __UpperCAmelCase : List[str] = WavaVecaForXVector.from_pretrained(UpperCamelCase , config=UpperCamelCase ) __UpperCAmelCase : Tuple = downstream_dict["connector.weight"] __UpperCAmelCase : str = downstream_dict["connector.bias"] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __UpperCAmelCase : int = downstream_dict[ f"model.framelevel_feature_extractor.module.{i}.kernel.weight" ] __UpperCAmelCase : Union[str, Any] = downstream_dict[f"model.framelevel_feature_extractor.module.{i}.kernel.bias"] __UpperCAmelCase : Tuple = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"] __UpperCAmelCase : Union[str, Any] = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"] __UpperCAmelCase : Dict = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"] __UpperCAmelCase : Union[str, Any] = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"] __UpperCAmelCase : int = downstream_dict["objective.W"] return model @torch.no_grad() def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Dict: """simple docstring""" __UpperCAmelCase : Union[str, Any] = torch.load(UpperCamelCase , map_location="cpu" ) __UpperCAmelCase : Optional[Any] = checkpoint["Downstream"] __UpperCAmelCase : int = WavaVecaConfig.from_pretrained(UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = WavaVecaFeatureExtractor.from_pretrained( UpperCamelCase , return_attention_mask=UpperCamelCase , do_normalize=UpperCamelCase ) __UpperCAmelCase : Dict = hf_config.architectures[0] if arch.endswith("ForSequenceClassification" ): __UpperCAmelCase : List[Any] = convert_classification(UpperCamelCase , UpperCamelCase , UpperCamelCase ) elif arch.endswith("ForAudioFrameClassification" ): __UpperCAmelCase : List[str] = convert_diarization(UpperCamelCase , UpperCamelCase , UpperCamelCase ) elif arch.endswith("ForXVector" ): __UpperCAmelCase : str = convert_xvector(UpperCamelCase , UpperCamelCase , UpperCamelCase ) else: raise NotImplementedError(f"S3PRL weights conversion is not supported for {arch}" ) if hf_config.use_weighted_layer_sum: __UpperCAmelCase : Optional[Any] = checkpoint["Featurizer"]["weights"] hf_feature_extractor.save_pretrained(UpperCamelCase ) hf_model.save_pretrained(UpperCamelCase ) if __name__ == "__main__": A = argparse.ArgumentParser() parser.add_argument( """--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model.""" ) parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""") parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""") A = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
77
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[int] = question_encoder snake_case_ : Optional[int] = generator snake_case_ : Optional[Any] = self.question_encoder def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' if os.path.isfile(__magic_name__ ): raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) snake_case_ : str = os.path.join(__magic_name__ , '''question_encoder_tokenizer''' ) snake_case_ : List[Any] = os.path.join(__magic_name__ , '''generator_tokenizer''' ) self.question_encoder.save_pretrained(__magic_name__ ) self.generator.save_pretrained(__magic_name__ ) @classmethod def lowerCamelCase (cls , __magic_name__ , **__magic_name__ ) -> Any: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case_ : List[str] = kwargs.pop('''config''' , __magic_name__ ) if config is None: snake_case_ : int = RagConfig.from_pretrained(__magic_name__ ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.question_encoder , subfolder='''question_encoder_tokenizer''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained( __magic_name__ , config=config.generator , subfolder='''generator_tokenizer''' ) return cls(question_encoder=__magic_name__ , generator=__magic_name__ ) def __call__(self , *__magic_name__ , **__magic_name__ ) -> Tuple: '''simple docstring''' return self.current_tokenizer(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> Dict: '''simple docstring''' return self.generator.batch_decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' return self.generator.decode(*__magic_name__ , **__magic_name__ ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Any = self.question_encoder def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.generator def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "longest" , __magic_name__ = None , __magic_name__ = True , **__magic_name__ , ) -> BatchEncoding: '''simple docstring''' warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''' , __magic_name__ , ) if max_length is None: snake_case_ : Dict = self.current_tokenizer.model_max_length snake_case_ : List[str] = self( __magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , max_length=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case_ : Optional[int] = self.current_tokenizer.model_max_length snake_case_ : Union[str, Any] = self( text_target=__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , padding=__magic_name__ , max_length=__magic_name__ , truncation=__magic_name__ , **__magic_name__ , ) snake_case_ : str = labels['''input_ids'''] return model_inputs
60
0
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Dict ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = int(snake_case_ ) assert noofclusters < len(snake_case_ ) # Find out the dimensionality UpperCAmelCase_ = len(vectors[0] ) # Will help select random centroids from among the available vectors UpperCAmelCase_ = list(range(len(snake_case_ ) ) ) shuffle(snake_case_ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. UpperCAmelCase_ = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION UpperCAmelCase_ = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points UpperCAmelCase_ = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(snake_case_ ) ] ##These nodes will assign the centroid Variables the appropriate ##values UpperCAmelCase_ = tf.placeholder("float64" , [dim] ) UpperCAmelCase_ = [] for centroid in centroids: cent_assigns.append(tf.assign(snake_case_ , snake_case_ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) UpperCAmelCase_ = [tf.Variable(0 ) for i in range(len(snake_case_ ) )] ##These nodes will assign an assignment Variable the appropriate ##value UpperCAmelCase_ = tf.placeholder("int32" ) UpperCAmelCase_ = [] for assignment in assignments: cluster_assigns.append(tf.assign(snake_case_ , snake_case_ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input UpperCAmelCase_ = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors UpperCAmelCase_ = tf.reduce_mean(snake_case_ , 0 ) ##Node for computing Euclidean distances # Placeholders for input UpperCAmelCase_ = tf.placeholder("float" , [dim] ) UpperCAmelCase_ = tf.placeholder("float" , [dim] ) UpperCAmelCase_ = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(snake_case_ , snake_case_ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input UpperCAmelCase_ = tf.placeholder("float" , [noofclusters] ) UpperCAmelCase_ = tf.argmin(snake_case_ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. UpperCAmelCase_ = tf.initialize_all_variables() # Initialize all variables sess.run(snake_case_ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. UpperCAmelCase_ = 1_00 for _ in range(snake_case_ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(snake_case_ ) ): UpperCAmelCase_ = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. UpperCAmelCase_ = [ sess.run(snake_case_ , feed_dict={va: vect, va: sess.run(snake_case_ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input UpperCAmelCase_ = sess.run( snake_case_ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(snake_case_ ): # Collect all the vectors assigned to this cluster UpperCAmelCase_ = [ vectors[i] for i in range(len(snake_case_ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location UpperCAmelCase_ = sess.run( snake_case_ , feed_dict={mean_input: array(snake_case_ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments UpperCAmelCase_ = sess.run(snake_case_ ) UpperCAmelCase_ = sess.run(snake_case_ ) return centroids, assignments
78
import inspect import unittest from transformers import ViTMSNConfig 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 ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=30 , __magic_name__=2 , __magic_name__=3 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=5 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.02 , __magic_name__=None , ) -> List[Any]: '''simple docstring''' snake_case_ : List[str] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : List[Any] = image_size snake_case_ : Optional[int] = patch_size snake_case_ : Optional[Any] = num_channels snake_case_ : Optional[Any] = is_training snake_case_ : List[Any] = use_labels snake_case_ : Optional[int] = hidden_size snake_case_ : Optional[Any] = num_hidden_layers snake_case_ : Union[str, Any] = num_attention_heads snake_case_ : Optional[Any] = intermediate_size snake_case_ : Any = hidden_act snake_case_ : List[str] = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : List[str] = type_sequence_label_size snake_case_ : Union[str, Any] = initializer_range snake_case_ : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case_ : Any = (image_size // patch_size) ** 2 snake_case_ : int = num_patches + 1 def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : List[Any] = None if self.use_labels: snake_case_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : int = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = ViTMSNModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : List[str] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = self.type_sequence_label_size snake_case_ : Tuple = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : Any = model(__magic_name__ , labels=__magic_name__ ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case_ : Optional[int] = 1 snake_case_ : List[str] = ViTMSNForImageClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() snake_case_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ : Any = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ : Optional[int] = config_and_inputs snake_case_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : List[Any] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () lowerCamelCase_ : Optional[int] = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False lowerCamelCase_ : int = False lowerCamelCase_ : Optional[int] = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[Any] = ViTMSNModelTester(self ) snake_case_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Any = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , nn.Linear ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ , snake_case_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Tuple = model_class(__magic_name__ ) snake_case_ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : Optional[int] = [*signature.parameters.keys()] snake_case_ : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __magic_name__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__magic_name__ ) @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : str = ViTMSNModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' torch.manual_seed(2 ) snake_case_ : List[str] = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__magic_name__ ) snake_case_ : str = self.default_image_processor snake_case_ : str = prepare_img() snake_case_ : int = image_processor(images=__magic_name__ , return_tensors='''pt''' ).to(__magic_name__ ) # forward pass with torch.no_grad(): snake_case_ : Optional[int] = model(**__magic_name__ ) # verify the logits snake_case_ : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __magic_name__ ) snake_case_ : List[Any] = torch.tensor([-0.0_803, -0.4_454, -0.2_375] ).to(__magic_name__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __magic_name__ , atol=1e-4 ) )
60
0
from collections import deque from .hash_table import HashTable class UpperCAmelCase_ ( __lowerCamelCase ): def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ): super().__init__(*_lowerCAmelCase , **_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : List[Any] = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = self.values[key] def __UpperCAmelCase ( self ): return ( sum(self.charge_factor - len(_lowerCAmelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(_lowerCAmelCase ) == 0 ): return key return super()._collision_resolution(_lowerCAmelCase , _lowerCAmelCase )
79
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''', } class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[Any] = '''efficientnet''' def __init__(self , __magic_name__ = 3 , __magic_name__ = 600 , __magic_name__ = 2.0 , __magic_name__ = 3.1 , __magic_name__ = 8 , __magic_name__ = [3, 3, 5, 3, 5, 5, 3] , __magic_name__ = [32, 16, 24, 40, 80, 112, 192] , __magic_name__ = [16, 24, 40, 80, 112, 192, 320] , __magic_name__ = [] , __magic_name__ = [1, 2, 2, 2, 1, 2, 1] , __magic_name__ = [1, 2, 2, 3, 3, 4, 1] , __magic_name__ = [1, 6, 6, 6, 6, 6, 6] , __magic_name__ = 0.25 , __magic_name__ = "swish" , __magic_name__ = 2560 , __magic_name__ = "mean" , __magic_name__ = 0.02 , __magic_name__ = 0.001 , __magic_name__ = 0.99 , __magic_name__ = 0.5 , __magic_name__ = 0.2 , **__magic_name__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**__magic_name__ ) snake_case_ : List[str] = num_channels snake_case_ : Tuple = image_size snake_case_ : Union[str, Any] = width_coefficient snake_case_ : Tuple = depth_coefficient snake_case_ : Optional[Any] = depth_divisor snake_case_ : Optional[int] = kernel_sizes snake_case_ : str = in_channels snake_case_ : Optional[Any] = out_channels snake_case_ : int = depthwise_padding snake_case_ : Optional[Any] = strides snake_case_ : Any = num_block_repeats snake_case_ : Optional[Any] = expand_ratios snake_case_ : Union[str, Any] = squeeze_expansion_ratio snake_case_ : Union[str, Any] = hidden_act snake_case_ : Union[str, Any] = hidden_dim snake_case_ : Any = pooling_type snake_case_ : List[str] = initializer_range snake_case_ : str = batch_norm_eps snake_case_ : Optional[int] = batch_norm_momentum snake_case_ : Optional[Any] = dropout_rate snake_case_ : List[str] = drop_connect_rate snake_case_ : Union[str, Any] = sum(__magic_name__ ) * 4 class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = version.parse('''1.11''' ) @property def lowerCamelCase (self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase (self ) -> float: '''simple docstring''' return 1e-5
60
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : Union[str, Any] = { """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/config.json""", """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/config.json""", """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/config.json""", """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/config.json""", """bert-base-multilingual-uncased""": """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json""", """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json""", """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/config.json""", """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/config.json""", """bert-large-uncased-whole-word-masking""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json""" ), """bert-large-cased-whole-word-masking""": ( """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json""" ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json""" ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json""" ), """bert-base-cased-finetuned-mrpc""": """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json""", """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json""", """bert-base-german-dbmdz-uncased""": """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json""", """cl-tohoku/bert-base-japanese""": """https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json""", """cl-tohoku/bert-base-japanese-whole-word-masking""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json""" ), """cl-tohoku/bert-base-japanese-char""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json""" ), """cl-tohoku/bert-base-japanese-char-whole-word-masking""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json""" ), """TurkuNLP/bert-base-finnish-cased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json""" ), """TurkuNLP/bert-base-finnish-uncased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json""" ), """wietsedv/bert-base-dutch-cased""": """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json""", # See all BERT models at https://huggingface.co/models?filter=bert } class __UpperCamelCase ( _lowerCAmelCase ): __snake_case :int = 'bert' def __init__( self : Union[str, Any] , _lowerCAmelCase : Union[str, Any]=3_0522 , _lowerCAmelCase : List[str]=768 , _lowerCAmelCase : List[Any]=12 , _lowerCAmelCase : Union[str, Any]=12 , _lowerCAmelCase : List[str]=3072 , _lowerCAmelCase : List[Any]="gelu" , _lowerCAmelCase : str=0.1 , _lowerCAmelCase : str=0.1 , _lowerCAmelCase : Optional[Any]=512 , _lowerCAmelCase : Dict=2 , _lowerCAmelCase : Optional[Any]=0.02 , _lowerCAmelCase : Dict=1e-12 , _lowerCAmelCase : Optional[int]=0 , _lowerCAmelCase : Optional[Any]="absolute" , _lowerCAmelCase : str=True , _lowerCAmelCase : Dict=None , **_lowerCAmelCase : Optional[Any] , ) -> Optional[int]: """simple docstring""" super().__init__(pad_token_id=_lowerCAmelCase , **_lowerCAmelCase ) __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = hidden_act __lowercase = intermediate_size __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = position_embedding_type __lowercase = use_cache __lowercase = classifier_dropout class __UpperCamelCase ( _lowerCAmelCase ): @property def _a ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": __lowercase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __lowercase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
80
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) lowerCAmelCase_ = logging.getLogger(__name__) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser( description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)''' ) parser.add_argument( '''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.''' ) parser.add_argument( '''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.''' ) parser.add_argument('''--vocab_size''', default=3_0_5_2_2, type=int) lowerCAmelCase_ = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, '''rb''') as fp: lowerCAmelCase_ = pickle.load(fp) logger.info('''Counting occurrences for MLM.''') lowerCAmelCase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowerCAmelCase_ = [0] * args.vocab_size for k, v in counter.items(): lowerCAmelCase_ = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, '''wb''') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
60
0